IOptions, IOptionsSnapshot and IOptionsMonitor compared: singleton, scoped and singleton lifetimes, computed once versus per scope versus cached and rebuilt on change tokens, CurrentValue and OnChange, named options with Get(name), the captive-dependency error, the per-request rebinding cost of IOptionsSnapshot, and how to choose for singletons, request handlers and BackgroundService.
All three give you the same bound options; they differ in lifetime and freshness.
IOptions<T>: singleton, built once on first .Value, never changes, no named options. The default for settings that need a restart anyway.IOptionsSnapshot<T>: scoped, rebuilt once per request (per scope), supports Get(name). A request sees one consistent value. It can't go into singletons, and it rebinds on every request.IOptionsMonitor<T>: singleton, CurrentValue is cached and rebuilt when the configuration change token fires, supports Get(name) and OnChange. Use it in singletons and BackgroundService.Changes only arrive if a provider reloads (JSON files, App Configuration refresh), never from environment variables. The trade-off: fresher values mean code that must cope with values changing under it.
"They all resolve to the same options pipeline, configure, post-configure, validate, but they cache the result differently.
IOptions<T>is a singleton: the first.Valuebuilds the object and that's it for the life of the process. It doesn't support named options.IOptionsSnapshot<T>is scoped: it builds the object once per DI scope, which in ASP.NET Core means once per request, so if the JSON file changed, the next request sees the new value, and within one request the value is stable.IOptionsMonitor<T>is a singleton that keeps a cache per name and clears it when the configuration's change token fires;CurrentValuealways gives the latest, andOnChangelets me react.For example, at [company] we had a rate-limit threshold in Azure App Configuration that operations wanted to change without a deployment. The limiter was a singleton that copied
IOptions<RateLimitOptions>.Valueinto a field in its constructor, so changes never applied until a restart. Switching it toIOptionsMonitorand readingCurrentValueper decision made changes apply within the [30-second] refresh interval. The opposite problem bit another team: they injectedIOptionsSnapshotinto a singleton cache and got the 'cannot consume scoped service from singleton' error at start-up, thanks to scope validation in Development.My rule:
IOptionsby default;IOptionsMonitorin singletons, background services, or when I need to react to changes;IOptionsSnapshotonly when a request genuinely needs a per-request consistent view of reloadable settings, because it re-runs binding and validation on every request. And nothing reloads unless a provider reloads: environment variables never do."
IOptions<T> |
IOptionsSnapshot<T> |
IOptionsMonitor<T> |
|
|---|---|---|---|
| Lifetime | Singleton | Scoped | Singleton |
| Value computed | Once, lazily | Once per scope | Cached, rebuilt after a change |
| Sees reloads | No | Next request | Yes, CurrentValue |
| Named options | No (default name only) | Get(name) |
Get(name) |
| Change notification | No | No | OnChange |
| Inject into singleton | Yes | No (captive dependency) | Yes |
| Cost per access | Field read | Bind + validate once per request | Dictionary lookup |
| Consumer | Use | Why |
|---|---|---|
| Singleton service | IOptions or IOptionsMonitor |
Snapshot is scoped |
| Endpoint / controller | IOptions, or IOptionsSnapshot if reloadable and must be consistent within the request |
|
BackgroundService |
IOptionsMonitor, read CurrentValue each iteration |
Runs for the life of the process |
Typed HttpClient setup |
IOptions |
Handler pipeline is built rarely |
| Several instances of one shape (two blob accounts) | Named options via IOptionsMonitor.Get(name) |
A team switched a hot endpoint handling [2,000] requests a second from IOptions to IOptionsSnapshot "to be safe". Profiling showed binding and DataAnnotations validation on every request adding about [4%] CPU; moving back to IOptionsMonitor.CurrentValue kept live reload and removed the cost.
Checks whether the candidate understands options lifetimes and how configuration reloads really reach code.
Green flags
IOptionsMonitor.CurrentValue in singletons and background services.Red flags
IOptions reloads automatically.IOptionsSnapshot into a singleton. OptionsFactory<T>.Create(name)
(new T → configure → post-configure → validate)
▲
┌────────────────────────┼────────────────────────┐
│ │ │
UnnamedOptionsManager<T> OptionsManager<T> OptionsMonitor<T>
(IOptions, singleton) (IOptionsSnapshot, scoped) (IOptionsMonitor, singleton)
caches 1 value forever caches per name, per scope IOptionsMonitorCache<T>,
cleared by change tokens
appsettings.json edited
│ FileSystemWatcher
▼
JsonConfigurationProvider.Load() ─► provider change token fires
│
▼
ConfigurationRoot reload token fires
│
▼
ConfigurationChangeTokenSource<T> (registered by BindConfiguration)
│
▼
OptionsMonitor<T>: cache.TryRemove(name), then invoke OnChange listeners
│
▼
next CurrentValue ─► factory rebuilds and validates
If the new value fails validation, the rebuild throws OptionsValidationException at the place that reads CurrentValue, so a bad edit surfaces at run time even with ValidateOnStart.
Configure<T>("primary", section) registers an IConfigureNamedOptions<T> for that name. IOptions<T> always uses Options.DefaultName (the empty string). ConfigureAll<T> applies to every name.
Editors often write a file in several steps, and FileSystemWatcher raises several events, so OnChange may fire two or three times for one save. Debounce in the callback, or make the callback idempotent. Keep the IDisposable from OnChange and dispose it with the owning object.
ConfigMaps mounted as volumes are updated by swapping a symlink, which file watchers can miss. DOTNET_USE_POLLING_FILE_WATCHER=true switches to polling. ConfigMaps exposed as environment variables never update without a pod restart.
appsettings.json and call it again.IOptionsSnapshot into a singleton in Development and read the start-up error.OnChange and log each call; save the file once and count the callbacks.IOptionsMonitor.Get("a")/Get("b").bombardier or k6 and compare CPU in dotnet-counters.A singleton and a background service that pick up reloaded settings, plus named options.
// Program.cs
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<RateLimitOptions>().BindConfiguration("RateLimit").ValidateDataAnnotations().ValidateOnStart();
// Named options: two storage accounts with the same shape
builder.Services.Configure<StorageOptions>("invoices", builder.Configuration.GetSection("Storage:Invoices"));
builder.Services.Configure<StorageOptions>("images", builder.Configuration.GetSection("Storage:Images"));
builder.Services.AddSingleton<RequestThrottle>();
builder.Services.AddHostedService<CleanupWorker>();
var app = builder.Build();
app.MapGet("/storage/{name}", (string name, IOptionsMonitor<StorageOptions> m) => m.Get(name).Container);
app.Run();
public sealed class RateLimitOptions
{
[System.ComponentModel.DataAnnotations.Range(1, 10_000)] public int PermitsPerMinute { get; init; } = 600;
}
public sealed class StorageOptions { public string Container { get; init; } = ""; }
// Singleton: read CurrentValue on each decision; never copy .Value into a field
public sealed class RequestThrottle(IOptionsMonitor<RateLimitOptions> options)
{
public bool IsOverLimit(int countThisMinute) => countThisMinute >= options.CurrentValue.PermitsPerMinute;
}
public sealed class CleanupWorker(IOptionsMonitor<RateLimitOptions> options, ILogger<CleanupWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// React to changes; dispose the registration when the worker stops
using var _ = options.OnChange(o => logger.LogInformation("Limit changed to {Limit}", o.PermitsPerMinute));
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
var limit = options.CurrentValue.PermitsPerMinute; // fresh every iteration
logger.LogDebug("Cleaning with limit {Limit}", limit);
}
}
}
options.Value or CurrentValue into a field in a singleton's constructor. Why it is wrong: The field never changes, so reloads are ignored. Instead: Keep the IOptionsMonitor<T> and read CurrentValue when needed.IOptionsSnapshot<T> into a singleton or hosted service. Why it is wrong: It is scoped; scope validation throws, or without validation it is captured from the root scope and never refreshes. Instead: Use IOptionsMonitor<T>.IOptionsSnapshot everywhere "to get reloads". Why it is wrong: It rebinds and revalidates on every request. Instead: IOptions for static settings, IOptionsMonitor for reloadable ones.IOptions<T> for named options. Why it is wrong: It only returns the default (unnamed) instance, so properties look empty. Instead: Use IOptionsMonitor<T>.Get(name) or IOptionsSnapshot<T>.Get(name).OnChange without debouncing. Why it is wrong: It can fire several times per save. Instead: Debounce or make the callback idempotent.ValidateOnStart protects reloads. Why it is wrong: A later invalid edit throws OptionsValidationException wherever CurrentValue is read. Instead: Validate changes before publishing them, and alert on that exception.Live reload is a feature with a cost: any value that can change at run time must be safe to change mid-flight. A connection-pool size or an HttpClient base address read once at start-up won't magically follow a reload, so I decide per setting whether it is restart-only or live, and only live settings go through IOptionsMonitor. For anything operational, like thresholds and kill switches, I'd usually prefer feature flags in Azure App Configuration with a refresh interval over editing files on running instances.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
IOptions<T> |
Restart-only settings, most cases | None | Settings ops must change live |
IOptionsMonitor<T> |
Singletons, workers, live thresholds | Code must tolerate changes; validation can throw at read | Values baked into long-lived objects at start-up |
IOptionsSnapshot<T> |
Per-request consistency of reloadable settings | Rebind + validate per request | Hot paths, singletons |
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
ASP.NET Core configuration is a layered key-value store. IConfiguration merges an ordered list of providers into one flat, case-insensitive dictionary. WebApplication.CreateBuilder adds, in order: appsettings.json, appsettings.{Environment}.json, user secrets (only in Development), environment variables and command-line arguments. When two providers set the same key, the one added last wins, so an environment variable on the server overrides the JSON file you shipped.
:, e.g. ConnectionStrings:Default.__ instead, e.g. ConnectionStrings__Default, because : is not allowed in Linux variable names.The trade-off: layering lets one build artifact run everywhere, but a value can come from five places, so you need to know the order to find out which one won.
How to tell it (STAR)
**S:** During a scraping incident on our public API at [company], operations lowered the rate limit in App Configuration, but traffic from the attacker stayed at about [1,200] requests a minute. **T:** I had to find out why a configuration change wasn't applying and make limits changeable without a restart. **A:** I confirmed the configuration itself refreshed by checking the debug view in staging, then found the limiter copied `IOptions.Value` into a field in its constructor. I restarted the instances to stop the bleeding, then changed the limiter to `IOptionsMonitor` and read `CurrentValue` per decision, with a test that changes configuration at run time and asserts the new limit applies. **R:** The next limit change applied within the [30-second] refresh interval, with no restart, and we added a review check against caching options in singletons.
Last updated 23 Nov 2026.