📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T>? Explain their lifetimes, how and when each sees configuration changes, how named options work, and which one you would use in a singleton, a controller and a background service.

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.

Mid-Level Theory Intermediate aspnet-core configuration dependency-injection ioptionsmonitor ioptionssnapshot options-pattern

🎯 Key points

  • IOptions<T>: singleton, built once on first .Value and then fixed for the process lifetime: it does not pick up later configuration changes; no named options
  • IOptionsSnapshot<T>: scoped, rebuilt once per scope (per request) when accessed, by design even if nothing changed; supports Get(name); cannot be injected into singletons
  • IOptionsMonitor<T>: singleton, CurrentValue cached per name and invalidated by change tokens, Get(name), OnChange callback
  • Reloads only happen when the provider reloads (JSON with reloadOnChange, App Configuration refresh); environment variables never change
  • Named options: Configure<T>("name", ...) and Get("name") for several instances of the same shape
  • Because IOptionsSnapshot re-runs binding (reflection) and validation per request, Microsoft's docs warn of a performance cost on hot paths
  • Singletons and BackgroundService use IOptionsMonitor and read CurrentValue each time; capturing .Value in a field defeats reloading
  • OnChange can fire more than once per file save; debounce and dispose the returned IDisposable

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 .Value builds 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; CurrentValue always gives the latest, and OnChange lets 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>.Value into a field in its constructor, so changes never applied until a restart. Switching it to IOptionsMonitor and reading CurrentValue per decision made changes apply within the [30-second] refresh interval. The opposite problem bit another team: they injected IOptionsSnapshot into a singleton cache and got the 'cannot consume scoped service from singleton' error at start-up, thanks to scope validation in Development.

My rule: IOptions by default; IOptionsMonitor in singletons, background services, or when I need to react to changes; IOptionsSnapshot only 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."


Comparison

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

Which to use where

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)

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands options lifetimes and how configuration reloads really reach code.

Green flags

  • States the three lifetimes correctly and the captive-dependency problem.
  • Knows reloads depend on the provider (files, App Configuration), not environment variables.
  • Uses IOptionsMonitor.CurrentValue in singletons and background services.
  • Mentions named options and the per-request cost of snapshots.

Red flags

  • Thinks IOptions reloads automatically.
  • Injects IOptionsSnapshot into a singleton.
  • Believes changing an App Service setting updates a running process without restart.

📚 Learn in depth

1. Same factory, different caches

                       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

2. How a change reaches the monitor

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.

3. Named options

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.

4. Duplicate notifications

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.

5. Kubernetes and mounted files

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.

Try it yourself

  1. Inject all three into one endpoint and return their values; edit appsettings.json and call it again.
  2. Inject IOptionsSnapshot into a singleton in Development and read the start-up error.
  3. Register OnChange and log each call; save the file once and count the callbacks.
  4. Register two named options and resolve them with IOptionsMonitor.Get("a")/Get("b").
  5. Benchmark 10,000 requests using snapshot versus monitor with bombardier or k6 and compare CPU in dotnet-counters.

💻 Code

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);
        }
    }
}

⚠ Common mistakes

  • Mistake: Copying 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.
  • Mistake: Injecting 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>.
  • Mistake: Using 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.
  • Mistake: Expecting reloads from environment variables or Kubernetes ConfigMap env vars. Why it is wrong: They are read once at process start. Instead: Use a reloadable source (mounted file with polling, App Configuration with refresh) or restart.
  • Mistake: Asking 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).
  • Mistake: Doing heavy work in OnChange without debouncing. Why it is wrong: It can fire several times per save. Instead: Debounce or make the callback idempotent.
  • Mistake: Assuming 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions injecting IOptionsSnapshot into a singleton. Why: Checks they can diagnose captive dependencies and know what ValidateScopes does.
    How to answer

    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.

  2. When: Candidate mentions reloadOnChange or which providers reload. Why: Checks understanding of the providers that feed the options and which of them can change at run time.
    How to answer

    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.

    • Hierarchy is flattened with :, e.g. ConnectionStrings:Default.
    • Environment variables use __ 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.

🛠 Real-world problems: how you handle them

Rate-limit change in App Configuration never took effect
Situation
A public API in Azure Australia East with [6] instances throttled abusive clients with a singleton limiter. Operations lowered the limit in Azure App Configuration during a scraping incident, but nothing changed.
Signals
Request rate from the abusive IP range stayed at [1,200] per minute in Application Insights; App Configuration showed the new value; the app logged no change.
Investigation
Checked `GetDebugView()` on a diagnostics endpoint in a staging slot: configuration had the new value after the refresh interval, so the provider worked. Read the limiter: its constructor copied `IOptions<RateLimitOptions>.Value.PermitsPerMinute` into a readonly field. `IOptions` never rebuilds, and even `IOptionsMonitor` would not help with a copied field.
Resolution
Immediate: restarted the instances to pick up the value. Fix: injected `IOptionsMonitor<RateLimitOptions>` and read `CurrentValue` on each decision, logging changes through `OnChange`.
Prevention
Classified settings as restart-only or live in the options class XML comments; added an integration test that changes an in-memory configuration value, triggers reload and asserts the limiter sees it; added a code-review checklist item against caching options values in singletons.

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.

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me