
IOptions, IOptionsSnapshot or IOptionsMonitor? Config Changes Are Not Automatic
- كاتب موثّق
- .NET 10
محتويات المقال
Recommendations:Enabled to false in appsettings.json, no restart needed, because the file reloads automatically. Someone makes the change. The endpoint keeps calling the slow service until a restart forty minutes later. The runbook was half right: the file did reload. The service that reads the flag never looked at it again.
The common misconception
IOptions<T> gives you live settings. When appsettings.json changes, the next read of options.Value returns the new values.
WebApplication.CreateBuilder loads the JSON files with reloadOnChange: true, so the configuration really does change while the app runs. Reading IConfiguration["Recommendations:Enabled"] directly returns the new value right away. Microsoft's docs demonstrate editing a file and refreshing the page without a restart. And on a developer machine, the app restarts so often that a stale value rarely survives long enough to notice.
What actually happens
Configuration reloads; options objects are built from it
RecommendationOptions. Configuration is the live source; the options object is a copy made at some moment. Whether you ever see a change depends on when that copy is made again, and each interface answers that differently. Reading IConfiguration directly would always be fresh, but you'd trade typed properties and validation for string keys scattered through the code.
IOptions<T>: built once
IOptions<T>: built onceIOptions<T> is registered as a singleton. Its Value is created on first access and kept for the app's lifetime, so changes made after startup are never read. It also doesn't support named options. That's the right behavior for settings that should only change with a deployment, and it's the cheapest of the three.
IOptionsSnapshot<T>: rebuilt per request
IOptionsSnapshot<T>: rebuilt per requestIOptionsSnapshot<T> is scoped. The options are computed once per request, when first accessed, and stay the same for the rest of that request. That consistency is useful: a request never sees half old and half new settings. The cost is a rebind on every request, which the docs flag as a possible significant performance penalty. And because it's scoped, it can't be injected into a singleton.
IOptionsMonitor<T>: the current value, any time
IOptionsMonitor<T>: the current value, any timeIOptionsMonitor<T> is a singleton, so any can use it. CurrentValue returns the latest bound value, and OnChange registers a callback that runs when the source changes. That makes it the only one of the three a singleton can use to follow changes. OnChange returns an IDisposable; dispose it when the object that registered the callback goes away, or the callback keeps it alive.
Only some sources change at all
The kill switch, fixed
RecommendationOptions class, with a bool Enabled and a [Range(1, 50)] int MaxItems:
using Microsoft.Extensions.Options;var builder = WebApplication.CreateBuilder(args);builder.Services.Configure<RecommendationOptions>( builder.Configuration.GetSection("Recommendations"));builder.Services.AddSingleton<RecommendationService>();var app = builder.Build();app.MapGet("/recommendations", (RecommendationService service) => service.IsEnabled ? Results.Ok(new[] { "book-42" }) : Results.NoContent());app.Run();public sealed class RecommendationService(IOptions<RecommendationOptions> options){ // IOptions binds once: a reloaded file never reaches this property public bool IsEnabled => options.Value.Enabled;}using Microsoft.Extensions.Options;var builder = WebApplication.CreateBuilder(args);builder.Services.AddOptions<RecommendationOptions>() .BindConfiguration("Recommendations") .ValidateDataAnnotations() .ValidateOnStart(); // a bad value fails at startup, not on first usebuilder.Services.AddSingleton<RecommendationService>();var app = builder.Build();app.MapGet("/recommendations", (RecommendationService service) => service.IsEnabled ? Results.Ok(new[] { "book-42" }) : Results.NoContent());app.Run();public sealed class RecommendationService( IOptionsMonitor<RecommendationOptions> options){ // CurrentValue is the latest bound value: read it on every call public bool IsEnabled => options.CurrentValue.Enabled;}appsettings.json while the app ran: within a few seconds, IConfiguration, IOptionsSnapshot and IOptionsMonitor all reported Enabled as false; IOptions still said true. One more detail: the monitor version only works because IsEnabled reads CurrentValue on each call. Copy options.CurrentValue into a field in the constructor and you've rebuilt the IOptions bug with extra steps.
IOptionsSnapshot<T> into a singleton and, in Development, the app refuses to start: "Cannot consume scoped service ... from singleton". In Production, that scope check is off by default, so the app starts, the singleton keeps the first snapshot forever, and you're back to a value that never changes.
Which one to inject
IOptions<T> | IOptionsSnapshot<T> | IOptionsMonitor<T> | |
|---|---|---|---|
CurrentValue | |||
How to apply it in your project
Decide which settings must change live Most settings, such as connection strings and URLs, should change only with a deployment: keep IOptions<T>. Flags, limits and thresholds you may need to flip under pressure are the candidates for live reload.Use the monitor in singletons, read it late For live settings in singletons, inject IOptionsMonitor<T>and readCurrentValuewhere the value is used. UseIOptionsSnapshot<T>in scoped code that needs one consistent view per request.Never cache the value in a field Search long-lived services for .Valueor.CurrentValueassigned in a constructor. Each one freezes the setting no matter which interface it came from.Rehearse a bad reload On a staging server, save an invalid value and watch what fails. If the answer is "every request", either keep that setting restart-only or make the code that reads it handle OptionsValidationException.
Key takeaways
The configuration reloads when appsettings.jsonchanges; whether your code sees it depends on which options interface you inject.IOptions<T>is built once,IOptionsSnapshot<T>once per request, andIOptionsMonitor<T>gives the current value whenever you read it.Singletons can follow changes only through IOptionsMonitor<T>, and only if they readCurrentValueat the point of use.Reloads re-run validation, so an invalid edit can make every read throw; environment variables never reload at all.
التعليقات (0)