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.
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.
"The options pattern is really a small DI pipeline. Every time you call
Configure<SmtpOptions>(section)you're registering anIConfigureOptions<SmtpOptions>singleton. When something first asks for the options,OptionsFactory<T>creates a new instance, runs everyIConfigureOptionsin registration order, then everyIPostConfigureOptions, then everyIValidateOptions, and caches the result according to which interface you used: forever forIOptions<T>, per name until a change token fires forIOptionsMonitor<T>, per scope forIOptionsSnapshot<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 withservices.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 scopedDbContext. Options are configuration-shaped DI, so the same lifetime rules apply."
| 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 |
| 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 |
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.
Checks whether the candidate understands options as a DI pipeline (configure, post-configure, validate) and applies DI lifetime rules to it.
Green flags
OptionsFactory and the configure → post-configure → validate orderConfigure<TDep> or an IConfigureOptions<T> class for service dependenciesIOptions/IOptionsMonitor being singletons to the no-scoped-dependency ruleBuildServiceProvider in registration is wrong (ASP0000)Red flags
BuildServiceProvider to get a service for configurationConfigure and PostConfigureservices.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).
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.
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.
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.
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>.
Configure and one PostConfigure that each append to a list property; print the list to see the order.IConfigureOptions<T> a scoped dependency, inject IOptions<T> with ValidateScopes = true, and read the exception; then try IOptionsSnapshot<T>.BuildServiceProvider() in Program.cs with a singleton that logs its constructor; count the constructor calls and look for the ASP0000 warning.JwtBearerOptions without a name and check that the handler doesn't see your change.IOptionsSnapshot<T>.Value per request against IOptionsMonitor<T>.CurrentValue.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);
}
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.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.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>.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.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.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.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.
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:
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;builder.Build() for start-up work.Trade-off: deferring moves failures from start-up to first use, so pair it with ValidateOnBuild.
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.
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.
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.
Last updated 23 Nov 2026.