IOptionsSnapshot: The Snapshot Your Singleton Froze
Ops rotated the SMTP password in App Configuration. The JSON file on disk updated. IConfiguration fired its change token. The next order confirmation still authenticated with the old password and 535'd. EmailSender is a singleton. It took IOptionsSnapshot<SmtpOptions> in the constructor. IOptionsSnapshot is a scoped service. A singleton that asks for it in Production does not throw. The snapshot is minted when that singleton is first constructed, and it never sees another scope. Reloads keep happening. That instance does not care.
Development had been "fine." ValidateScopes is on there. The same constructor throws InvalidOperationException before the first request. Production turns the check off. The host builds, the singleton resolves a snapshot from the root provider, and the bug waits for the first secret rotation.
Three types, three lifetimes
The options stack registers three facades over the same TOptions class:
// Microsoft.Extensions.Options — simplified
services.TryAddSingleton<IOptions<SmtpOptions>, OptionsManager<SmtpOptions>>();
services.TryAddScoped<IOptionsSnapshot<SmtpOptions>, OptionsManager<SmtpOptions>>();
services.TryAddSingleton<IOptionsMonitor<SmtpOptions>, OptionsMonitor<SmtpOptions>>();
OptionsManager<T> keeps a private OptionsCache<T> on the instance. IOptions<T> is one manager for the process, so .Value is computed on first access and then served from that cache for the rest of the process. IOptionsSnapshot<T> is a new manager per DI scope — per HTTP request, per IServiceScope you create for a job. .Value is computed once for that scope, then frozen until the scope dies. A request that reads Timeout twice gets the same object even if appsettings.json is rewritten in between. That is the point of a snapshot.
IOptionsMonitor<T> is the singleton that listens. It uses the process-wide IOptionsMonitorCache<T>, registers IOptionsChangeTokenSource<T> when you bind a reloadable section, clears that name on change, and exposes CurrentValue, Get(name), and OnChange. The contract of IOptions<T> is unnamed options, no reload API, safe to inject anywhere. Do not use it as a change feed.
What Production actually constructs
builder.Services.Configure<SmtpOptions>(
builder.Configuration.GetSection("Smtp"));
builder.Services.AddSingleton<EmailSender>();
public sealed class EmailSender(IOptionsSnapshot<SmtpOptions> snapshot)
{
private readonly SmtpOptions _smtp = snapshot.Value;
public Task SendAsync(string to, string body, CancellationToken ct)
=> SendCoreAsync(_smtp, to, body, ct);
}
In Development the host's default service provider sets ValidateScopes (and usually ValidateOnBuild). Resolving EmailSender from the root throws: cannot consume scoped IOptionsSnapshot<SmtpOptions> from singleton EmailSender. You fix it before lunch.
In Production ValidateScopes is false. The root provider creates the scoped manager itself. That manager is not tied to a request. It is not disposed until the process dies. snapshot.Value runs IOptionsFactory once, fills the manager's private cache, and _smtp holds that object. A later IConfiguration reload rebuilds what a new scope would see. This field is not a new scope.
The Data Protection key ring is the same shape of bug: Development on one machine hides a farm problem. Here Development throws and Production captures.
Turn ValidateScopes on where you live, not only where you F5:
builder.Host.UseDefaultServiceProvider((_, o) =>
{
o.ValidateScopes = true;
});
The monitor is the singleton API
A singleton that must follow config takes IOptionsMonitor<T> and reads it at use, not at construction:
public sealed class EmailSender(IOptionsMonitor<SmtpOptions> monitor)
{
public Task SendAsync(string to, string body, CancellationToken ct)
=> SendCoreAsync(monitor.CurrentValue, to, body, ct);
}
CurrentValue is Get(Options.DefaultName). It is the current unnamed instance. It is not a copy you own. Treat TOptions as immutable after bind. monitor.CurrentValue.Password = newPassword mutates the cached object every consumer shares.
Capturing the monitor and then doing _smtp = monitor.CurrentValue in the constructor is the snapshot bug with extra steps. The field is still a copy of a moment.
OnChange is for work you cannot repeat on the next call — rebuilding an SmtpClient, swapping a HttpClient header, invalidating a derived cache. The callback runs on a thread-pool thread, not a request. It has no HttpContext and no scoped DbContext. Swap a reference:
public sealed class EmailSender : IDisposable
{
private readonly IDisposable _onChange;
private SmtpOptions _smtp;
public EmailSender(IOptionsMonitor<SmtpOptions> monitor)
{
_smtp = monitor.CurrentValue;
_onChange = monitor.OnChange(next => Volatile.Write(ref _smtp, next));
}
public Task SendAsync(string to, string body, CancellationToken ct)
=> SendCoreAsync(Volatile.Read(ref _smtp), to, body, ct);
public void Dispose() => _onChange.Dispose();
}
A singleton may keep that subscription for process lifetime. A scoped service that calls OnChange and does not dispose leaks one handler per request. The incident post's billing API disposed a connection inside that callback. The callback is a store, not a place to tear down scoped resources.
IOptionsSnapshot<T> remains the right injection for a controller, a Minimal API filter, a scoped processor. You want the values as they were when the request started, and you do not want them mutating under a SaveChanges that is still running. Do not "upgrade" those to IOptionsMonitor for style. Lifetime is the feature.
Named options are invisible to IOptions
IOptions<T>.Value is the default name, "". Named registrations do not fill it.
builder.Services.AddOptions<SmtpOptions>("alerts")
.BindConfiguration("Smtp:Alerts")
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddOptions<SmtpOptions>("receipts")
.BindConfiguration("Smtp:Receipts")
.ValidateDataAnnotations()
.ValidateOnStart();
A singleton that injects IOptions<SmtpOptions> and reads .Value.Host gets new SmtpOptions() — empty strings, zero timeouts — because nothing ran Configure for the default name. No exception. The first send uses whatever defaults the SMTP client has, often localhost. IOptionsSnapshot<T>.Get("alerts") and IOptionsMonitor<T>.Get("alerts") are the APIs that take a name. CurrentValue is still the unnamed instance. If you only registered names, CurrentValue is the empty object too.
ValidateOnStart() is per registration. It validates that named instance when the host starts, not on first send. Without it, ValidateDataAnnotations() and Validate(...) run inside IOptionsFactory.Create on first Get / .Value. A background sender that is idle until a message arrives can boot green and throw OptionsValidationException twenty minutes later. Fail the host in startup, not after the replica is already Ready.
Configure runs in registration order. PostConfigure runs after every Configure. Last Configure wins among configures; PostConfigure always wins after that. Use PostConfigure for computed defaults — derive From from Host if From is empty — not a second Configure that a later bind can overwrite.
Reloads, scopes, and workers
WebApplication.CreateBuilder loads appsettings.json with reloadOnChange: true. Azure App Configuration's provider has its own poll interval and change token. Neither pushes values into a field you already copied.
A hosted service is a singleton. ExecuteAsync must not take IOptionsSnapshot<T> on the constructor for the same reason EmailSender must not. Inject IOptionsMonitor<T>, or create a scope per iteration:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await using var scope = services.CreateAsyncScope();
var snapshot = scope.ServiceProvider.GetRequiredService<IOptionsSnapshot<SmtpOptions>>();
await TickAsync(snapshot.Value, stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
The inner scope is the snapshot's lifetime. The delay sits outside it so you are not holding a fake request open. GetRequiredService<IOptionsSnapshot<T>> from the root in that loop is the captured instance again.
BindConfiguration("Smtp") and Configure<T>(configuration.GetSection("Smtp")) both hook a change token for that section. The freeze is still the cache you already copied into a field, not the binder.
Which injection to take
| Consumer | Inject | Read |
|---|---|---|
| Singleton, value needed at call time | IOptionsMonitor<T> | CurrentValue or Get(name) on each use |
| Singleton, derived client to rebuild | IOptionsMonitor<T> | OnChange, dispose the subscription |
| Controller / scoped worker | IOptionsSnapshot<T> | .Value or Get(name) once per scope |
| Code that must not see reloads and has no name | IOptions<T> | .Value |
| Named SMTP, named retry, named blob | Snapshot or Monitor | Get("alerts"), never .Value alone |
| Boot-time "this config is illegal" | ValidateOnStart() | Fail the host, do not wait for first send |
The password in App Configuration was current. The singleton still had the object IOptionsSnapshot built when the root provider first constructed EmailSender. Inject a monitor and read it when you send, or inject a snapshot only into something the container will construct per scope. The type name is the lifetime. Production will not save you from mixing them.
Keep reading
Data Protection Keys: The Cookie the Other Instance Could Not Read
Cookie auth, antiforgery, and TempData encrypt with the Data Protection key ring. The default ring is local. A second instance, a slot swap, or a recycled container mints a ring the first one never had.
EF Core ExecuteUpdate: SaveChanges Never Ran, and Neither Did Your Interceptor
ExecuteUpdate sends SQL now. It skips SaveChanges, the tracker, and your audit interceptor. Stamp columns in the SET, or the tracked entity lies.
Pass the CancellationToken or the Work Continues After the Client Left
ASP.NET Core binds CancellationToken to the aborted request. Forward it to EF Core and HttpClient, and do not turn a client disconnect into a 500.
IHttpClientFactory: Stop Creating HttpClient Per Request
Why new HttpClient() in a .NET service exhausts sockets under load, and how IHttpClientFactory plus a named client fixes DNS without freezing the handler forever.
CQRS in Practice: When It's Worth the Complexity and When It Isn't
A clear-eyed look at Command Query Responsibility Segregation — what it actually is, how to implement it in .NET, when it pays off, and when it's unnecessary complexity.
Fixing NuGet Error: Unable to Load the Service Index for Source
A step-by-step guide to diagnosing and resolving NuGet package source errors in Visual Studio and dotnet CLI.
Newsletter
New posts, straight to your inbox
One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.
Comments
- No comments yet. Be the first.