In ASP.NET Core, how do IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T> differ in lifetime and reload behaviour, and which do you inject where?
answer
- singleton, scoped, singleton
- computed once, per request, on change
- Snapshot cannot go into a singleton
- CurrentValue and OnChange
- named instances: Get(name)
basics
~20 sIOptions<T> is a singleton computed once and never reloaded; IOptionsSnapshot<T> is scoped and recomputed per request; IOptionsMonitor<T> is a singleton whose CurrentValue updates on reload and which raises OnChange. Singletons take IOptions or IOptionsMonitor, never IOptionsSnapshot.
solid answer
~40 s`IOptions<T>` is registered as a singleton; `.Value` is built on first read and cached for the life of the app, so it never sees a reloaded `appsettings.json` and has no named instances. `IOptionsSnapshot<T>` is scoped: each request builds its own instance, so a request sees a consistent, current value, and `Get(name)` reads named options; because it is scoped it cannot be injected into a singleton, and Development's scope validation reports it as a scoped service consumed from a singleton. `IOptionsMonitor<T>` is a singleton with a cache that is cleared when the configuration's change token fires: `CurrentValue` returns the latest value, `Get(name)` reads named options, and `OnChange` registers a listener. Use `IOptions` for values fixed at startup, `IOptionsSnapshot` in request-scoped services that want per-request freshness, and `IOptionsMonitor` in singletons and background services.
code
csharp · 16 linesbuilder.Services.AddOptions<PaymentGatewayOptions>()
.BindConfiguration("PaymentGateway");
// singleton: must not take IOptionsSnapshot
builder.Services.AddSingleton<GatewayClientFactory>();
public sealed class GatewayClientFactory(IOptionsMonitor<PaymentGatewayOptions> options)
{
public Uri BaseUri => new(options.CurrentValue.BaseUrl);
}
// scoped: per-request snapshot is fine
public sealed class CheckoutService(IOptionsSnapshot<PaymentGatewayOptions> options)
{
public int TimeoutSeconds => options.Value.TimeoutSeconds;
}go deeper
Remember the three names and that IOptions does not reload while the other two can.
Give each interface's DI lifetime, when it recomputes, which support named options, and why the snapshot cannot be injected into a singleton.
Choose by consumer lifetime and cost, read CurrentValue per use, dispose OnChange registrations, and plan for a reload that fails validation.
Decide which settings may change at runtime at all; for the rest, IOptions makes immutability explicit and removes a class of mid-flight surprises.
## Three interfaces over one factory All three read from the same pipeline: the options factory creates a `T`, runs every configure action, every post-configure action, then every validator. They differ in **how long they keep the result**: | Interface | DI lifetime | Recomputed | Named options | Change callback | |---|---|---|---|---| | `IOptions<T>` | Singleton | Never after first `.Value` | No (default name only) | No | | `IOptionsSnapshot<T>` | **Scoped** | Once per scope (each request) | `Get(name)` | No | | `IOptionsMonitor<T>` | Singleton | When the source's change token fires | `Get(name)` | `OnChange` | ## IOptions<T> The implementation caches the first value it builds. If `appsettings.json` reloads, the configuration changes but `IOptions<PaymentGatewayOptions>.Value` keeps returning the startup object. That is a feature for settings that must not move under a running app, such as the gateway's base URL, and the cheapest of the three. ## IOptionsSnapshot<T> Each scope gets its own options manager with a private cache. In a web app a scope is a request, so the first read in a request binds a fresh object and later reads in the same request reuse it. Two consequences: - **Consistency inside a request**, freshness across requests. - **Cost**: binding runs again on every request that reads it, which matters for large sections on hot paths. Because it is scoped, a singleton cannot take it. With scope validation on (the default in Development) the container throws "Cannot consume scoped service ... from singleton ..."; in Production nothing checks, and resolving it from the root makes it live as long as the app, so it silently stops refreshing. ## IOptionsMonitor<T> The monitor is a singleton with a cache per name. The binding call (`Configure<T>(section)` or `BindConfiguration`) registers a change-token source tied to the configuration; when `appsettings.json` reloads, the monitor removes the cached instance, rebuilds it and invokes the `OnChange` listeners with the new value and its name. ```csharp public sealed class GatewayHealthProbe : BackgroundService { private readonly IOptionsMonitor<PaymentGatewayOptions> _gateway; public GatewayHealthProbe(IOptionsMonitor<PaymentGatewayOptions> gateway, ILogger<GatewayHealthProbe> log) { _gateway = gateway; gateway.OnChange((o, name) => log.LogInformation("Gateway {Name} now {Url}", name, o.BaseUrl)); } protected override async Task ExecuteAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { var current = _gateway.CurrentValue; // read each loop, never cache await Task.Delay(TimeSpan.FromSeconds(current.ProbeSeconds), ct); } } } ``` Points interviewers probe: 1. **Read `CurrentValue` each time**; storing it in a field turns the monitor back into `IOptions`. 2. **`OnChange` returns an `IDisposable`**; dispose it when the listener's owner goes away, or the monitor keeps the owner alive. 3. **Listeners can fire more than once per save**, because file watchers raise several events. 4. **An invalid reload throws**: the monitor drops the cached value and rebuilds it, so if validation fails the next `CurrentValue` throws `OptionsValidationException` instead of returning the last good value. ## Middleware is a special case A conventional middleware class is constructed once for the app, so its constructor behaves like a singleton's: take `IOptions<T>` or `IOptionsMonitor<T>` there. Its `InvokeAsync(HttpContext context, ...)` method can declare extra parameters that are resolved per request, which is where `IOptionsSnapshot<T>` may appear safely. ## Choosing - A value fixed at startup, read anywhere: `IOptions<T>`. - A scoped service (controller, Minimal API handler dependency) that should see edits on the next request: `IOptionsSnapshot<T>`. - A singleton, hosted service or middleware constructor that must see edits, or code that must react to them: `IOptionsMonitor<T>`. - Named instances: `IOptionsSnapshot<T>.Get(name)` or `IOptionsMonitor<T>.Get(name)`; `IOptions<T>` only exposes the default name. ## Interview checklist - Lifetimes: singleton, scoped, singleton. - Reload: never, per request, on change. - Never inject the snapshot into a singleton. - `CurrentValue`, `Get(name)` and `OnChange` on the monitor.
- What happens if a singleton takes IOptionsSnapshot<T> in its constructor?`IOptionsSnapshot<T>` is scoped. In Development, scope validation is on and the container throws "Cannot consume scoped service ... from singleton ..." when the singleton is built. Without validation the snapshot is resolved from the root scope and lives forever, so it never refreshes. Use `IOptionsMonitor<T>` instead.
- A reload writes an invalid value into a section that IOptionsMonitor<T> validates. What do callers see?The monitor clears its cached instance and rebuilds it; validation fails and `OptionsValidationException` is thrown. It does not keep the last good value, so every later `CurrentValue` read throws until the configuration is fixed. Code that must survive bad edits should catch it or keep its own last known good copy.
- Why might IOptionsSnapshot<T> show up in a profiler on a hot endpoint?Each request creates a new options manager, and the first read in that request runs the factory: binding, post-configure and validation. For a large section read on every request that is repeated work; `IOptionsMonitor<T>` caches until a change and is usually the cheaper reload-aware choice.
IOptions is a laminated menu printed on opening day; IOptionsSnapshot is a fresh paper menu handed to each table as it sits down; IOptionsMonitor is the chalkboard behind the counter that staff rewrite and anyone can glance at, with a bell that rings when it changes.
- IOptions<T> picks up appsettings.json changes because the file reloads on change.
- IOptionsSnapshot<T> is a singleton that refreshes its value every request.
- Storing IOptionsMonitor<T>.CurrentValue in a field keeps it up to date.
- IOptions<T>.Value supports named options through an overload.
- IOptionsMonitor<T> keeps the last valid value when a reload fails validation.