The options pattern: binding configuration sections to strongly typed classes with Configure<T>, AddOptions<T>().Bind/BindConfiguration, how ConfigurationBinder maps keys to properties (case-insensitive, conversions, collections, missing keys, ErrorOnUnknownConfiguration), IConfigureOptions and PostConfigure for code-based setup, the binding source generator for AOT, and why injecting IConfiguration into services is an anti-pattern.
The options pattern binds a configuration section to a strongly typed class once, at the composition root, and injects IOptions<T> (or IOptionsSnapshot<T> / IOptionsMonitor<T>) where it is needed. You register it with builder.Services.AddOptions<PaymentOptions>().BindConfiguration("Payments"), usually chained with ValidateDataAnnotations().ValidateOnStart().
The ConfigurationBinder matches keys to public properties case-insensitively and converts strings to the property type; missing keys leave defaults.
Injecting IConfiguration everywhere instead spreads magic strings, hides what a class really depends on, makes tests build fake configuration, and skips validation. The trade-off: one small class and a registration per section, in exchange for typed, validated, discoverable settings.
"The options pattern is how I turn configuration into typed objects. I write a class like
PaymentOptionswith the properties of a section, register it once withAddOptions<PaymentOptions>().BindConfiguration("Payments"), and services takeIOptions<PaymentOptions>in their constructor. The binder walks the section, matches keys to properties case-insensitively, converts the strings,"00:00:10"to aTimeSpan,"3"to anint, and fills lists and dictionaries from child sections. Keys that are missing leave the property's default, which is why I give every property a sensible default in the class.I always chain validation:
ValidateDataAnnotations()for simple rules andValidateOnStart()so the app refuses to start with a missing API key instead of failing on the first payment. When a value depends on another service or needs computing, I useIConfigureOptions<T>orPostConfigure, which still produces the same options object. For Native AOT the reflection binder isn't trim-safe, so the configuration binding source generator takes over.Why not just inject
IConfiguration? Becauseconfig["Payments:Timout"]with a typo returns null at run time and nothing tells you. The class signature no longer says what it needs, a unit test has to build a fake configuration tree, and there is nowhere to hang validation. The mistake I see is the halfway house: binding withGetSection().Get<T>()inside a constructor on every resolve. Options gives you one place that defines the shape of a section, one place that validates it, and constructors that tell the truth."
| Registration | Notes |
|---|---|
services.AddOptions<T>().BindConfiguration("Section") |
Preferred; returns an OptionsBuilder<T> for chaining validation |
services.AddOptions<T>().Bind(config.GetSection("Section")) |
Same, when you already have a section |
services.Configure<T>(config.GetSection("Section")) |
Older style, no builder to chain |
services.Configure<T>(o => o.Retries = 3) |
Code-only values |
services.ConfigureOptions<MyConfigureOptions>() |
IConfigureOptions<T> that can use injected services |
services.PostConfigure<T>(o => ...) |
Runs after all Configure calls: computed defaults |
| Configuration | Property | Result |
|---|---|---|
Payments:Timeout = "00:00:10" |
TimeSpan Timeout |
10 seconds |
Payments:Regions:0, :1 |
List<string> Regions |
Two items |
Payments:Fees:AUD = "0.3" |
Dictionary<string, decimal> Fees |
{ AUD: 0.3 } |
| key missing | int Retries { get; init; } = 3 |
Stays 3 |
Payments:Retries = "three" |
int Retries |
InvalidOperationException when bound |
Payments:Retires = 5 (typo) |
Ignored, unless ErrorOnUnknownConfiguration = true |
A payments service had 23 config["..."] reads across 11 classes. Two had typos that returned null and fell back to hard-coded values nobody remembered. Moving to four options classes with ValidateOnStart turned both bugs into start-up failures in the test environment, and the constructor of every service now listed exactly which settings it used.
Checks that the candidate turns configuration into typed, validated dependencies rather than string lookups.
Green flags
AddOptions<T>().BindConfiguration() with validation and ValidateOnStart.IConfiguration (hidden dependencies, no validation, testing).IConfigureOptions/PostConfigure for computed values.Red flags
IConfiguration["..."] throughout services.AddOptions<T>() registers the open-generic options infrastructure once. Each piece has one job:
IOptions<T> → UnnamedOptionsManager<T> (singleton) calls the factory once, caches forever
IOptionsSnapshot<T> → OptionsManager<T> (scoped) calls the factory once per scope (request)
IOptionsMonitor<T> → OptionsMonitor<T> (singleton) caches per name, rebuilds after change tokens fire
IOptionsFactory<T> → OptionsFactory<T> (transient) builds an instance: new T, configure, post-configure, validate
IOptionsMonitorCache<T> → OptionsCache<T> (singleton) the per-name cache the monitor uses
The three interfaces you inject differ only in how long they keep what the factory built; the configuration, post-configuration and validation steps are identical. BindConfiguration adds an IConfigureOptions<T> that binds the section, plus an IOptionsChangeTokenSource<T> so the monitor knows when to rebuild.
OptionsFactory<T>.Create(name) runs a fixed pipeline every time it builds an instance:
new T() (public parameterless constructor)
│
├─► every IConfigureNamedOptions<T> / IConfigureOptions<T> in registration order
│ (BindConfiguration, Configure(o => ...), ConfigureOptions<X>)
├─► every IPostConfigureOptions<T> in registration order
└─► every IValidateOptions<T> ── any failure ─► OptionsValidationException
So a Configure registered later overrides an earlier one, and PostConfigure always runs last.
ConfigurationBinder.Bind uses reflection: for each public property with a setter (including init), it looks for a child key with the same name, ignoring case. Scalars are converted with the type's TypeConverter using the invariant culture, so "0.3" is a decimal on every server and "0,3" fails. Collections are filled from child sections; for arrays, items are appended to existing ones. BinderOptions.BindNonPublicProperties and ErrorOnUnknownConfiguration change the defaults.
Setting <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator> (automatic when PublishAot is on) makes the compiler intercept Bind, Get<T> and BindConfiguration calls and generate binding code, so trimming does not remove the properties the reflection binder would need.
Class needs IConfiguration Class needs IOptions<PaymentOptions>
→ can read ANY key → depends on exactly one section
→ string keys, no validation → typed, validated at start-up
→ test: build config tree → test: Options.Create(new PaymentOptions { ... })
TimeSpan, a List<string> and a Dictionary<string,int>; print the result as JSON."abc" into an int property and read the exception message.ErrorOnUnknownConfiguration; see the error.Configure<T> twice with different values and check which wins; add PostConfigure and check again.Options.Create(new PaymentOptions { ... }) and no configuration at all.Binding, validating and consuming a section, and testing the consumer without any configuration.
// PaymentOptions.cs
using System.ComponentModel.DataAnnotations;
namespace Shop.Payments;
public sealed class PaymentOptions
{
public const string Section = "Payments";
[Required, Url] public string BaseUrl { get; init; } = "";
[Range(typeof(TimeSpan), "00:00:01", "00:01:00")] public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(10);
[Range(0, 5)] public int Retries { get; init; } = 3;
public List<string> Regions { get; init; } = [];
}
// Program.cs
using Shop.Payments;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<PaymentOptions>()
.BindConfiguration(PaymentOptions.Section, o => o.ErrorOnUnknownConfiguration = true) // typos fail loudly
.ValidateDataAnnotations()
.ValidateOnStart(); // bad config stops the app at start-up
// Typed client configured from options: the dependency is explicit
builder.Services.AddHttpClient<PaymentGateway>((sp, http) =>
{
var o = sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<PaymentOptions>>().Value;
http.BaseAddress = new Uri(o.BaseUrl);
http.Timeout = o.Timeout;
});
var app = builder.Build();
app.MapPost("/pay", (PaymentGateway gw, CancellationToken ct) => gw.PingAsync(ct));
app.Run();
public sealed class PaymentGateway(HttpClient http)
{
public async Task<IResult> PingAsync(CancellationToken ct) =>
(await http.GetAsync("health", ct)).IsSuccessStatusCode ? Results.Ok() : Results.StatusCode(502);
}
// Unit test: no configuration tree needed
var options = Microsoft.Extensions.Options.Options.Create(new PaymentOptions { BaseUrl = "https://test", Retries = 1 });
IConfiguration into services and reading keys with strings. Why it is wrong: Typos return null, dependencies are hidden and nothing is validated. Instead: Bind a section to an options class and inject IOptions<T>.config.GetSection("X").Get<T>() inside a constructor. Why it is wrong: It rebinds with reflection on every resolve and bypasses validation and change tracking. Instead: Register with AddOptions<T>().BindConfiguration(...).const Section and validate required properties with ValidateOnStart."0,5" with a comma decimal separator or "18/11/2026". Why it is wrong: The binder always converts with CultureInfo.InvariantCulture, whatever the server's culture, so a comma decimal fails conversion (or is misread) and the bind throws InvalidOperationException. Instead: Store invariant formats in configuration: 0.5, ISO 8601 dates (2026-11-18), hh:mm:ss for TimeSpan.OptionsFactory<T> creates the instance with new T(), so AddOptions<T>() requires a public parameterless constructor (the T : class registration has a new() expectation at run time), and the binder then sets properties. Instead: Keep a public parameterless constructor (the implicit one is fine) and use init properties with defaults; that gives read-only-after-binding semantics without breaking the factory.Program.cs with builder.Configuration.Get<T>() and also registering them. Why it is wrong: You now have two sources of truth that can diverge after PostConfigure or validation. Instead: Resolve IOptions<T> from the provider when you need the value at start-up, or keep the read in one place.IOptions<T>.Value is a shared singleton instance; every consumer sees the change, with no thread safety. Instead: Treat options as read-only; use init setters.Options classes are part of the service's contract with operations, so I design them like an API: small, one per concern, with safe defaults and validation that explains what is wrong. The pattern also gives you a seam for testing that IConfiguration never did. Where I stop is wrapping options in further abstractions (ISettingsProvider around IOptions<T>): the framework already provides the abstraction, lifetimes and change tracking.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
AddOptions<T>().BindConfiguration |
Any structured setting used by services | One class per section | A single value read once in Program.cs |
IConfigureOptions<T> |
Values derived from other services or secrets | An extra class | Plain binding |
IConfiguration directly |
Composition root, library extension methods taking a section | Magic strings | Inside business services |
| Binding source generator | Native AOT, trimming | Build-time generation | Nothing to lose: turn it on for AOT apps |
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.
:, e.g. ConnectionStrings:Default.__ 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.
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.
Last updated 23 Nov 2026.