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

📚 Interview question

How do options work together with dependency injection? Explain IConfigureOptions<T>, IPostConfigureOptions<T> and the order they run in, how to configure options that depend on other services, which lifetimes those configure classes are resolved with, and why calling BuildServiceProvider to get a service inside Configure is wrong.

The options pipeline as a DI feature: IConfigureOptions, IConfigureNamedOptions, IPostConfigureOptions and IValidateOptions, their execution order in OptionsFactory, configuring options from other services with AddOptions<T>().Configure<TDep> or ConfigureOptions<T>, lifetime rules and the BuildServiceProvider anti-pattern.

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

🎯 Key points

  • Every Configure call registers an IConfigureOptions<T> singleton; OptionsFactory<T> runs them in registration order
  • Order: all Configure (including named), then all PostConfigure, then IValidateOptions; ConfigureAll/PostConfigureAll apply to every name
  • AddOptions<T>().Configure<TDep1..TDep5>((o, dep) => ...) or a class implementing IConfigureOptions<T> registered with ConfigureOptions<T>() for service dependencies
  • IOptions<T> is a singleton that builds the value once; IOptionsMonitor<T> is also registered as a singleton, caching built instances per name in IOptionsMonitorCache<T> and rebuilding a name when its change token fires
  • Because both are singletons, their configure classes are resolved from the root provider: no scoped dependencies
  • IOptionsSnapshot<T> is scoped and recomputed per scope: right for per-request reloaded values in scoped services, but it costs a full configure pass per request
  • Calling BuildServiceProvider inside registration creates a second container with duplicate singletons (analyser ASP0000); use a configure class instead
  • Framework options (JwtBearerOptions, HttpClientFactoryOptions) are named, so configure them with the right name

⏱ 30-second answer

Options are built by OptionsFactory<T> from services you register in DI. Each Configure<T>(...) adds an IConfigureOptions<T> singleton; PostConfigure adds an IPostConfigureOptions<T>; validation adds IValidateOptions<T>. The factory runs all configures in registration order, then all post-configures, then validators. When options need another service (a secret client, IHostEnvironment), you use AddOptions<T>().Configure<TDep>((o, dep) => ...) or a class implementing IConfigureOptions<T> registered with ConfigureOptions<T>(), so the container injects the dependency. The catch is lifetimes: IOptions<T> and IOptionsMonitor<T> are singletons, so those configure classes can't depend on scoped services. And never call BuildServiceProvider() in registration code: it builds a second container with its own singletons.

🗣 Full answer (senior)

How I would answer this in an interview

"The options pattern is really a small DI pipeline. Every time you call Configure<SmtpOptions>(section) you're registering an IConfigureOptions<SmtpOptions> singleton. When something first asks for the options, OptionsFactory<T> creates a new instance, runs every IConfigureOptions in registration order, then every IPostConfigureOptions, then every IValidateOptions, and caches the result according to which interface you used: forever for IOptions<T>, per name until a change token fires for IOptionsMonitor<T>, per scope for IOptionsSnapshot<T>.

Because those steps are services, they can have dependencies. If the JWT signing settings come from a service that reads Key Vault, I write a ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions> that takes the service in its constructor and register it with services.ConfigureOptions<ConfigureJwtBearerOptions>(). For small cases, AddOptions<T>().Configure<IHostEnvironment>((o, env) => ...) does the same inline, with up to five dependencies. For example, at [company] we [configured the authentication options for each environment's identity provider this way], and it removed [a block of if-statements on environment names from Program.cs].

The mistake I see is people needing a service during registration and calling builder.Services.BuildServiceProvider() to get it. That builds a second container: singletons are created twice, disposables leak, and the analyser ASP0000 warns about it. The other trap is lifetimes: IOptions<T> is a singleton, so its configure classes are resolved from the root and can't take a scoped DbContext. Options are configuration-shaped DI, so the same lifetime rules apply."


The pipeline

Step Registered by Runs
IConfigureOptions<T> / IConfigureNamedOptions<T> Configure, Bind, BindConfiguration, ConfigureOptions<TSetup>() First, in registration order
IPostConfigureOptions<T> PostConfigure, PostConfigureAll After all configures
IValidateOptions<T> Validate, ValidateDataAnnotations, [OptionsValidator] Last; ValidateOnStart runs it at start-up

Which interface, which lifetime

Consumer interface Lifetime Recomputed Configure classes may depend on
IOptions<T> Singleton Never Singletons only
IOptionsMonitor<T> Singleton On change token, per name Singletons only
IOptionsSnapshot<T> Scoped Every scope Scoped or singleton

Production example

In [an API with Entra ID and a partner identity provider], two named JwtBearerOptions schemes were configured by one IConfigureNamedOptions class that took IOptionsMonitor<IdentityProvidersOptions> and IHostEnvironment. That replaced a BuildServiceProvider call that had been creating a second HybridCache and a second connection multiplexer to Redis, which had doubled Redis connections from about 60 to 120 per instance.

🔍 What the interviewer is checking

Checks whether the candidate understands options as a DI pipeline (configure, post-configure, validate) and applies DI lifetime rules to it.

Green flags

  • Describes OptionsFactory and the configure → post-configure → validate order
  • Uses Configure<TDep> or an IConfigureOptions<T> class for service dependencies
  • Links IOptions/IOptionsMonitor being singletons to the no-scoped-dependency rule
  • Knows why BuildServiceProvider in registration is wrong (ASP0000)

Red flags

  • Calls BuildServiceProvider to get a service for configuration
  • Thinks registration order decides between Configure and PostConfigure
  • Doesn't know framework options are named

📚 Learn in depth

1. What Configure actually registers

services.Configure<SmtpOptions>(section)
   -> AddOptions()  (TryAdd: IOptions<>, IOptionsSnapshot<>, IOptionsMonitor<>, IOptionsFactory<>, IOptionsMonitorCache<>)
   -> AddSingleton<IOptionsChangeTokenSource<SmtpOptions>>(...)   // for reload
   -> AddSingleton<IConfigureOptions<SmtpOptions>>(new NamedConfigureFromConfigurationOptions<SmtpOptions>(name, section))

The open generic IOptions<> maps to UnnamedOptionsManager<> (singleton), IOptionsMonitor<> to OptionsMonitor<> (singleton), IOptionsSnapshot<> to OptionsManager<> (scoped), and IOptionsFactory<> to OptionsFactory<> (transient).

2. OptionsFactory

T options = new T()                       // or CreateInstance override
foreach IConfigureOptions<T> setup:       // registration order
    if setup is IConfigureNamedOptions<T>: setup.Configure(name, options)
    else if name == Options.DefaultName:   setup.Configure(options)
foreach IPostConfigureOptions<T> post:    post.PostConfigure(name, options)
foreach IValidateOptions<T> v:            collect failures -> OptionsValidationException
return options

The factory receives IEnumerable<IConfigureOptions<T>> and friends through its constructor, so whatever provider resolves the factory resolves the setup classes too.

3. Lifetimes in practice

UnnamedOptionsManager<T> is a singleton, so it resolves its factory (and all setup classes) from the root provider. A setup class depending on a scoped service would be resolved from the root: ValidateScopes throws in Development; in production you get a captive instance. OptionsManager<T> (behind IOptionsSnapshot<T>) is scoped, resolves a factory per scope and recomputes options every scope, which costs a full configure pass per request.

4. Options that depend on services

Two idioms:

AddOptions<T>().Configure<TDep1, TDep2>((o, d1, d2) => ...)   // up to five deps
services.ConfigureOptions<MySetup>()  // registers MySetup as IConfigureOptions/IPostConfigureOptions/IValidateOptions it implements

Both let the container inject dependencies when the options are first built, not at registration. That is the cure for BuildServiceProvider() in Program.cs, which constructs a second ServiceProvider from the same collection: duplicate singletons, leaked disposables and options that differ between the two containers.

5. Named options and framework options

Authentication handlers, HttpClientFactoryOptions and others are named options. JwtBearerOptions for the default scheme live under the name "Bearer", so Configure<JwtBearerOptions>(o => ...) (default name) does nothing; you need Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, ...) or IConfigureNamedOptions<T>.

Try it yourself

  1. Register two Configure and one PostConfigure that each append to a list property; print the list to see the order.
  2. Give an IConfigureOptions<T> a scoped dependency, inject IOptions<T> with ValidateScopes = true, and read the exception; then try IOptionsSnapshot<T>.
  3. Call BuildServiceProvider() in Program.cs with a singleton that logs its constructor; count the constructor calls and look for the ASP0000 warning.
  4. Configure JwtBearerOptions without a name and check that the handler doesn't see your change.
  5. Benchmark IOptionsSnapshot<T>.Value per request against IOptionsMonitor<T>.CurrentValue.

💻 Code

Options that depend on services, named framework options and the BuildServiceProvider fix (.NET 10):

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOptions<IdentityProviderOptions>()
    .BindConfiguration("Identity")
    .ValidateDataAnnotations()
    .ValidateOnStart();

// Inline dependency injection into options configuration.
builder.Services.AddOptions<ExportOptions>()
    .BindConfiguration("Export")
    .Configure<IHostEnvironment>((o, env) =>
        o.TempFolder ??= Path.Combine(env.ContentRootPath, "tmp"));

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
// A setup class with injected services, for the *named* JwtBearerOptions.
builder.Services.ConfigureOptions<ConfigureJwtBearer>();

// WRONG: builds a second container; singletons are created twice (analyser ASP0000).
// var idp = builder.Services.BuildServiceProvider().GetRequiredService<IOptions<IdentityProviderOptions>>();

var app = builder.Build();
app.Run();

public sealed class IdentityProviderOptions
{
    [System.ComponentModel.DataAnnotations.Required] public required string Authority { get; init; }
    [System.ComponentModel.DataAnnotations.Required] public required string Audience { get; init; }
}

public sealed class ExportOptions { public string? TempFolder { get; set; } }

// Resolved from the root provider (JwtBearerOptions is read through IOptionsMonitor),
// so it may only depend on singletons.
public sealed class ConfigureJwtBearer(IOptions<IdentityProviderOptions> idp, IHostEnvironment env)
    : IConfigureNamedOptions<JwtBearerOptions>
{
    public void Configure(string? name, JwtBearerOptions options)
    {
        if (name != JwtBearerDefaults.AuthenticationScheme) return;
        options.Authority = idp.Value.Authority;
        options.Audience = idp.Value.Audience;
        options.RequireHttpsMetadata = !env.IsDevelopment();
    }

    public void Configure(JwtBearerOptions options) => Configure(Options.DefaultName, options);
}

⚠ Common mistakes

  • Mistake: Calling builder.Services.BuildServiceProvider() to get a service during registration. Why it is wrong: it builds a second container with its own singletons and disposables. Instead: use AddOptions<T>().Configure<TDep> or an IConfigureOptions<T> class.
  • Mistake: Injecting a scoped service (such as a DbContext) into an IConfigureOptions<T> consumed through IOptions<T> or IOptionsMonitor<T>. Why it is wrong: both are singletons, so the setup class is resolved from the root provider; the scoped service becomes captive (stale data, concurrency exceptions, a DbContext never disposed) or ValidateScopes throws at first use. Instead: depend only on singletons, or read per-request data at use time instead of in options.
  • Mistake: Configuring JwtBearerOptions or other framework options without a name. Why it is wrong: they are named by scheme, so the default-name configuration is ignored and tokens are validated with the wrong authority. Instead: pass the scheme name or implement IConfigureNamedOptions<T>.
  • Mistake: Relying on PostConfigure registration order to run before a Configure registered later. Why it is wrong: all configures run before any post-configure, whatever the order in Program.cs. Instead: use PostConfigure deliberately for "final word" defaults.
  • Mistake: Using IOptionsSnapshot<T> everywhere "to be safe". Why it is wrong: it rebuilds the options every request (binder allocations on every call in a high-throughput API) and can't be injected into singletons. Instead: use IOptionsSnapshot<T> in scoped services that genuinely need a consistent, reloaded value per request; use IOptions<T> for static settings and IOptionsMonitor<T> for reloadable settings in singletons.
  • Mistake: Doing slow I/O (calling Key Vault) inside Configure. Why it is wrong: it runs on first resolution, often on a request thread, and blocks it. Instead: load secrets through the configuration provider at start-up, or warm options with ValidateOnStart.

🏛 Senior insight: trade-offs

Treat options configuration as code that runs inside the container, with the same lifetime rules as any other service. That framing answers most questions: why a configure class can't take a DbContext, why BuildServiceProvider is wrong, and why named framework options ignore your unnamed configuration. Keep setup classes small and free of I/O; if you need data from a database to build options, it's probably not configuration.

Option When it fits Cost When not to
Configure/BindConfiguration Values from configuration None Depends on services
AddOptions<T>().Configure<TDep> 1–5 singleton deps, small logic Lambda in Program.cs Logic grows; hard to test
IConfigureOptions<T> class + ConfigureOptions<T>() Reusable, testable, named options One class Trivial cases
PostConfigure Final defaults after all configuration Order surprises Primary configuration
BuildServiceProvider in registration Never in production code Second container Always

Measure with a startup trace if options binding seems slow, and check IOptionsSnapshot<T> hot paths with a profiler; per-request rebuilds show up as binder allocations.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions BuildServiceProvider or getting a service during start-up Why: Checks the consequences of building a second container
    How to answer

    services.BuildServiceProvider() takes a snapshot of the IServiceCollection and builds a second, independent root container. It has its own singleton cache, so every singleton resolved from it is a different instance from the app's (two caches, two connection pools); nothing disposes it, so its singletons and root-resolved disposables leak; registrations added later are missing; and scoped services resolved from its root effectively live for ever. The ASP0000 analyser warns about it.

    Instead, defer the work until the real container exists:

    • a factory delegate sp => new Foo(sp.GetRequiredService<IBar>()), which runs on first resolution from the real provider;
    • IConfigureOptions<T> (or AddOptions<T>().Configure<IDep>(...)) for options that need services;
    • a hosted service or code after builder.Build() for start-up work.

    Trade-off: deferring moves failures from start-up to first use, so pair it with ValidateOnBuild.

  2. When: Candidate mentions IValidateOptions or ValidateOnStart Why: Checks options validation and failing fast on bad configuration
    How to answer

    Options validation runs as the last step when an options object is built. ValidateDataAnnotations() applies attributes such as [Required], [Range] and [Url]; Validate(o => ..., "message") adds small rules; IValidateOptions<T> handles cross-property rules, named options or rules that need services.

    Without ValidateOnStart() validation is lazy: a missing key surfaces as a 500 on the first request that reads the options, possibly hours after the deployment looked healthy. With it, the host validates during start-up, the process exits with every failure listed, and the orchestrator keeps the old version serving.

    Nested objects need [ValidateObjectMembers] and collections [ValidateEnumeratedItems]. For Native AOT, the [OptionsValidator] source generator writes the DataAnnotations checks at compile time with no reflection.

    The trade-off: a few attributes and a class, in exchange for configuration errors becoming start-up errors with clear messages.

  3. When: Candidate mentions IOptionsSnapshot or IOptionsMonitor Why: Checks the lifetimes and reload behaviour of the options interfaces
    How to 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.

🛠 Real-world problems: how you handle them

BuildServiceProvider in Program.cs doubled Redis connections
Situation
An [order-tracking] API on .NET [10] in Azure Container Apps [Australia East], running [6] replicas, needed the Redis connection string from an options class while configuring authentication. A developer called `builder.Services.BuildServiceProvider()` to read it.
Signals
Azure Cache for Redis showed connected clients doubling from about [60] to [120] after the release, approaching the tier's limit. Start-up time grew by about [2] seconds. Logs showed the `RedisConnectionFactory` constructor message twice per replica.
Investigation
Searched the code for `BuildServiceProvider` and found the call; the build output also showed ASP0000 warnings that had been ignored. Confirmed with a debugger that two `ServiceProvider` instances existed, each with its own singleton `ConnectionMultiplexer`.
Resolution
Replaced the call with an `IConfigureNamedOptions<JwtBearerOptions>` class that takes `IOptions<RedisOptions>` through its constructor. Redeployed; connections dropped back to about [60].
Prevention
Promoted ASP0000 to an error with `TreatWarningsAsErrors` for that rule, added a Redis connected-clients alert at [80]% of the tier limit, and added a test that counts singleton constructions during host start-up.

How to tell it (STAR)

**S:** After a release of [our order-tracking API], Redis connected clients doubled to [around 120] and were heading for the tier limit. **T:** I needed to find the cause before the [evening peak]. **A:** The logs showed our Redis connection factory being constructed twice per replica. I searched for `BuildServiceProvider` and found someone had used it in `Program.cs` to read an options value while configuring authentication, which built a second container with its own singletons. I replaced it with a configure-options class that gets the value injected, made the ASP0000 analyser warning a build error, and added an alert on Redis connections. **R:** Connections went back to [about 60], start-up was [2 seconds] faster, and the analyser has blocked [three] similar attempts since.

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me