7.6 — IOptions vs IOptionsSnapshot vs IOptionsMonitor¶
← Roadmap · Section: 7. Configuration and Options Prev: 7.5 The IConfiguration API · Next: 7.7 Binding to POCOs
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
The options pattern binds a configuration section to a typed class, which services then inject instead of reading strings. There are three interfaces, and choosing wrong causes real bugs.
IOptions<T>— singleton. Read once at startup, never changes. The default.IOptionsSnapshot<T>— scoped. Re-read once per request, so it picks up changes.IOptionsMonitor<T>— singleton, but with live values and a change callback.
⚠️ IOptionsSnapshot<T> is scoped, so injecting it into a singleton is a captive dependency.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Options pattern | a technique | Binding a configuration section to a strongly-typed class. |
| Options class | a plain C# class | Properties matching the configuration keys. No base class or interface needed. |
Configure<T> |
a method | Binds a configuration section to T and registers the options interfaces. |
IOptions<T> |
an interface — singleton | Value read once at startup. Never updates. |
IOptionsSnapshot<T> |
an interface — scoped | Value re-read once per request. Picks up reloads. |
IOptionsMonitor<T> |
an interface — singleton | Always current, plus OnChange notifications. |
.Value |
a property | How you get the actual options object from IOptions or IOptionsSnapshot. |
.CurrentValue |
a property | The equivalent on IOptionsMonitor. Re-read each time. |
OnChange |
a method | Registers a callback fired when the underlying configuration reloads. |
| Named options | a feature | Several configured instances of one options type, distinguished by name. |
The concept¶
Why not just read IConfiguration?¶
// ✗ The stringly-typed way
public class OrderService(IConfiguration config)
{
public void Process()
{
var max = config.GetValue<int>("Orders:MaxItems"); // magic string
}
}
Three problems (7.5): the key is a string with no compile-time checking, a missing value silently becomes zero, and the class's real dependency — a number — is hidden behind a general-purpose object.
The options pattern fixes all three:
public class OrderOptions
{
public int MaxItems { get; set; } = 100;
public decimal AutoApproveUnder { get; set; }
public int ReservationMinutes { get; set; } = 15;
}
// ✓ Typed, validatable, and the dependency is explicit
public class OrderService(IOptions<OrderOptions> options)
{
private readonly OrderOptions _options = options.Value;
public void Process()
{
var max = _options.MaxItems; // a real property
}
}
⚠️ The three interfaces¶
This is the part interviews focus on, because the lifetimes differ and that has consequences.
| Lifetime | Value read | Sees config reloads? | Named options? | |
|---|---|---|---|---|
IOptions<T> |
Singleton | Once, at first use | ❌ No | ❌ |
IOptionsSnapshot<T> |
Scoped | Once per request | ✅ Yes | ✅ |
IOptionsMonitor<T> |
Singleton | Every access | ✅ Yes | ✅ |
A picture: three ways of knowing today's exchange rate.
IOptionsis a rate you wrote down when you opened the shop. Fast, and stale by evening.IOptionsSnapshotis checking the board once when each customer walks in. Consistent for that customer, fresh per customer.IOptionsMonitoris a live ticker on the wall. Always current, and it can change while you are mid-sentence.
That last point matters: with IOptionsMonitor, two reads of CurrentValue in one method can
return different objects. If a method needs consistency, read it into a local variable once.
How it works¶
The simple version — choosing¶
IOptions<T> is the right default. Most settings do not change while the application runs,
and it is the only one usable everywhere, including in singletons.
public class OrderService(IOptions<OrderOptions> options)
{
private readonly OrderOptions _options = options.Value; // read once, cache it
}
IOptionsSnapshot<T> when a setting can change and you want it per request:
public class PricingService(IOptionsSnapshot<PricingOptions> options)
{
// Fresh at the start of each request, consistent within it
private readonly PricingOptions _options = options.Value;
}
IOptionsMonitor<T> in singletons and background services that need current values:
public class RateLimiter(IOptionsMonitor<RateLimitOptions> monitor)
{
public bool IsAllowed(string clientId)
{
var limit = monitor.CurrentValue.RequestsPerMinute; // current every time
// ...
}
}
⚠️ The captive dependency trap¶
IOptionsSnapshot<T> is registered as scoped. So this is a captive dependency
(6.4):
// ✗ BROKEN — a singleton capturing a scoped service
public class PriceCache(IOptionsSnapshot<PriceOptions> options) // singleton
{
// The snapshot is resolved ONCE and held forever.
// It never updates, and it holds a request-scoped object for the app's lifetime.
}
With ValidateScopes enabled you get a startup exception naming both types. But that is
Development-only by default (6.13), so it starts
cleanly in production and quietly stops updating.
The fix in a singleton is IOptionsMonitor<T>, which is itself a singleton and still sees
changes:
// ✓ Singleton, and still current
public class PriceCache(IOptionsMonitor<PriceOptions> monitor)
{
public decimal Markup => monitor.CurrentValue.Markup;
}
The rule: IOptionsSnapshot in scoped services and controllers; IOptionsMonitor in
singletons.
Middleware is the case people forget — conventional middleware is a singleton
(5.5), so it needs
IOptionsMonitor, or IOptionsSnapshot as an InvokeAsync parameter.
OnChange — reacting to reloads¶
public class CacheManager : IDisposable
{
private readonly IDisposable? _subscription;
public CacheManager(IOptionsMonitor<CacheOptions> monitor)
{
_subscription = monitor.OnChange(options =>
{
// Fires when the underlying configuration reloads
ResizeCache(options.MaxSizeMb);
});
}
public void Dispose() => _subscription?.Dispose();
}
⚠️ Two things to be careful about.
Dispose the subscription, or the monitor holds a reference to your object forever — a memory leak (3.5).
OnChange can fire more than once for a single edit. File watchers often report a save as
two events, so the callback must be idempotent and cheap. Do not put expensive work directly
inside it.
How it actually works — named options¶
Several configured instances of one type, distinguished by name:
{
"Storage": {
"Primary": { "ConnectionString": "...", "Container": "prod" },
"Archive": { "ConnectionString": "...", "Container": "archive" }
}
}
builder.Services.Configure<StorageOptions>("Primary",
builder.Configuration.GetSection("Storage:Primary"));
builder.Services.Configure<StorageOptions>("Archive",
builder.Configuration.GetSection("Storage:Archive"));
public class BackupService(IOptionsSnapshot<StorageOptions> options)
{
private readonly StorageOptions _primary = options.Get("Primary");
private readonly StorageOptions _archive = options.Get("Archive");
}
⚠️ IOptions<T> does not support named options — it only ever gives you the default
instance. You need IOptionsSnapshot<T> or IOptionsMonitor<T> for Get(name).
This is how IHttpClientFactory configures named clients, and how authentication configures
multiple schemes.
The deeper detail — what actually triggers a change¶
IOptionsSnapshot and IOptionsMonitor only see updates if the underlying provider reloads.
builder.Configuration.AddJsonFile("appsettings.json",
optional: false,
reloadOnChange: true); // ← without this, nothing ever changes
⚠️ In a container, editing the file is not a thing that happens. The image is immutable and
config comes from environment variables, which do not reload. So in most deployments
IOptionsSnapshot and IOptionsMonitor behave exactly like IOptions — the extra machinery
buys nothing.
They earn their place with a mounted ConfigMap in Kubernetes, or a Key Vault provider with a reload interval (7.4).
Use IOptions<T> unless you have a specific reason. See
7.9 for what reloading actually reaches.
Code¶
A realistic set showing each in its right place:
// Program.cs
builder.Services.Configure<OrderOptions>(builder.Configuration.GetSection("Orders"));
builder.Services.Configure<RateLimitOptions>(builder.Configuration.GetSection("RateLimit"));
// ✓ SCOPED service → IOptions is fine, since these settings do not change
public class OrderService(IOptions<OrderOptions> options) : IOrderService
{
private readonly OrderOptions _options = options.Value;
public bool CanAutoApprove(Order order)
=> order.Total < _options.AutoApproveUnder;
}
// ✓ SINGLETON that must see changes → IOptionsMonitor
public class RateLimitService(IOptionsMonitor<RateLimitOptions> monitor) : IRateLimitService
{
private readonly ConcurrentDictionary<string, Counter> _counters = new();
public bool IsAllowed(string clientId)
{
// Read ONCE into a local — CurrentValue could change between two reads
var options = monitor.CurrentValue;
var counter = _counters.GetOrAdd(clientId, _ => new Counter());
return counter.Increment(options.Window) <= options.RequestsPerMinute;
}
}
// ✓ Conventional middleware is a SINGLETON → IOptionsMonitor, not IOptionsSnapshot
internal class ApiKeyMiddleware(
RequestDelegate next,
IOptionsMonitor<SecurityOptions> monitor)
{
public async Task InvokeAsync(HttpContext context)
{
var options = monitor.CurrentValue;
// ...
await next(context);
}
}
The comment in the middle example is the subtle one. CurrentValue re-reads on every access, so:
// ✗ These two reads can see DIFFERENT objects
if (monitor.CurrentValue.Enabled)
Process(monitor.CurrentValue.BatchSize); // config could have reloaded in between
// ✓ One read, consistent for this operation
var options = monitor.CurrentValue;
if (options.Enabled)
Process(options.BatchSize);
Interview questions¶
Q: What is the options pattern and why use it over IConfiguration?
It binds a configuration section to a strongly-typed class that services inject, instead of
reading string keys. That fixes three problems with using IConfiguration directly: the keys are
magic strings with no compile-time checking, a missing value silently becomes a default rather
than failing, and the class's real dependency is hidden behind a general-purpose configuration
object that is awkward to fake in tests. With options the dependency is a plain typed class, and
it can be validated at startup.
Q: What is the difference between the three options interfaces?
IOptions<T> is a singleton whose value is read once and never changes — the right default for
settings that are fixed for the application's lifetime. IOptionsSnapshot<T> is scoped, so it is
re-read once per request and picks up configuration reloads, staying consistent within a single
request. IOptionsMonitor<T> is a singleton that reads the current value on every access and
also exposes an OnChange callback. The critical detail is the lifetimes: because
IOptionsSnapshot is scoped, injecting it into a singleton is a captive dependency, so
singletons and conventional middleware need IOptionsMonitor instead.
Q: When would you actually need something other than IOptions<T>?
Only when the configuration genuinely reloads at runtime, which is rarer than people assume. It
requires a provider with reloadOnChange enabled, and in most deployments configuration comes
from environment variables that never change, or a container image that is immutable — so
IOptionsSnapshot and IOptionsMonitor behave identically to IOptions and the extra machinery
buys nothing. They earn their place with a mounted Kubernetes ConfigMap or a Key Vault provider
configured with a reload interval.
Q: What is a subtlety of using IOptionsMonitor.CurrentValue?
It re-reads on every access, so two reads within the same method can return different objects if
the configuration reloads in between. That produces genuinely confusing bugs — checking a flag
and then using a related setting, and getting an inconsistent pair. So I read CurrentValue once
into a local variable at the start of an operation and use that throughout. The other subtlety is
that OnChange subscriptions must be disposed, or the monitor keeps a reference to your object
forever, and the callback can fire twice for a single file save.
Traps ⚠️¶
IOptionsSnapshot<T>is scoped, so injecting it into a singleton or conventional middleware is a captive dependency.ValidateScopescatches that in Development only, so it reaches production silently.IOptions<T>does not support named options.Get(name)needs snapshot or monitor.- Nothing reloads without
reloadOnChange: trueon the provider — and environment variables never reload at all. CurrentValuecan change between two reads. Capture it once per operation.OnChangesubscriptions leak unless disposed, and can fire twice per edit.IOptionsSnapshotin a background service throws — there is no scope (21.2).- Options classes need a parameterless constructor and settable properties, or binding silently produces defaults (7.7).
Related¶
- 7.5 The IConfiguration API — what this replaces in services
- 7.7 Binding to POCOs — how the class is populated
- 7.8 Options validation — failing fast on bad values
- 7.9 Reload on change — what actually updates
- 6.3 Service lifetimes — why scoped in singleton breaks
- 6.4 Captive dependencies — the trap in detail
- 5.5 Conventional middleware — a singleton that needs monitor