skip to content

Typed Settings & Validation

The options pattern binds a section to a class you inject as IOptions, IOptionsSnapshot or IOptionsMonitor, each with its own lifetime and reload story. Interviewers ask which to inject and when.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core, how do you bind the Mail section of appsettings.json to a MailOptions class and inject it into a service?

level: juniorimportance: must knowfreq 74%

answer

  1. the options pattern
  2. Configure<T>(GetSection(...)) or BindConfiguration
  3. IOptions<T>.Value in the constructor
  4. public settable properties, names match keys
  5. binding runs on first Value, not at registration

basics

~10 s

Register the section with builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail")) or AddOptions<MailOptions>().BindConfiguration("Mail"), then inject IOptions<MailOptions> and read .Value. Keys bind to public settable properties by name, ignoring case.

solid answer

~30 s

The options pattern maps a configuration section onto a plain class. `builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail"))` registers a binding; `builder.Services.AddOptions<MailOptions>().BindConfiguration("Mail")` does the same, resolves `IConfiguration` from DI and returns an `OptionsBuilder<MailOptions>` you can chain validation on. A service then takes `IOptions<MailOptions>` in its constructor and reads `.Value`. The binder matches keys to public properties with setters, ignoring case; keys with no property are ignored and properties with no key keep their initializer. Binding happens when `.Value` is first read, so a value like `"Port": "abc"` throws `InvalidOperationException` there, not at registration. Since .NET 10 an explicit JSON `null` overwrites the property's initializer with `null`.

code

csharp · 11 lines
csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOptions<MailOptions>()
    .BindConfiguration(MailOptions.SectionName);

builder.Services.AddScoped<OrderMailer>();

var app = builder.Build();
app.MapPost("/orders/{id}/confirm", (int id, OrderMailer mailer) =>
    mailer.SendConfirmationAsync($"customer-{id}@example.com"));
app.Run();

go deeper

for a junior

Recall Configure<T> with GetSection, injecting IOptions<T> and reading .Value, and that property names match the JSON keys.

for a middle

Explain BindConfiguration versus Configure<T>, the binder's matching rules, and that binding runs lazily on the first Value read.

for a senior

Make binding failures and typos surface at deploy time with ErrorOnUnknownConfiguration and startup validation, and audit the .NET 10 null-binding change on upgrade.

for a principal

Set a convention for settings classes, such as a SectionName constant and validation on every class, so configuration errors cannot reach production silently.

## The options pattern in one picture A subscription-box service sends order confirmations by mail. Instead of reading `Mail:SmtpHost`, `Mail:Port` and friends as strings all over the code, it binds the `Mail` section once onto a class: ```json { "Mail": { "SmtpHost": "smtp.boxes.internal", "Port": 587, "FromAddress": "[email protected]", "UseStartTls": true } } ``` ```csharp public sealed class MailOptions { public const string SectionName = "Mail"; public string SmtpHost { get; set; } = ""; public int Port { get; set; } = 25; public string FromAddress { get; set; } = ""; public bool UseStartTls { get; set; } } ``` ## Two ways to register the binding | Registration | What it gives you | |---|---| | `builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail"))` | Binds the section you pass; returns `IServiceCollection` | | `builder.Services.AddOptions<MailOptions>().BindConfiguration("Mail")` | Binds the path against the app's `IConfiguration` from DI; returns `OptionsBuilder<MailOptions>` for chaining `Validate...` calls | Both also register a change-token source, so reload-aware options interfaces notice when the underlying files change. `BindConfiguration` is the shape to prefer when you will add validation, because the builder carries the chain. ## Consuming it ```csharp public sealed class OrderMailer(IOptions<MailOptions> options) { private readonly MailOptions _mail = options.Value; public Task SendConfirmationAsync(string to) => Task.CompletedTask; // connect to _mail.SmtpHost:_mail.Port ... } ``` `IOptions<T>` is registered by the options infrastructure; you never register `MailOptions` itself. Injecting `MailOptions` directly fails to resolve unless you add that registration yourself. ## How the binder matches values The configuration binder walks the section and the class together: - **Names match case-insensitively**: `smtphost` fills `SmtpHost`. - **Public properties with a setter** are bound by default; `BinderOptions.BindNonPublicProperties` widens that to non-public setters. - **Missing keys leave the initializer**: no `Port` key means `Port` stays `25`. - **Extra keys are ignored**, unless `BinderOptions.ErrorOnUnknownConfiguration` is set, which makes them throw. - **Strings are converted** with the property type's converter; `"Port": "abc"` throws `InvalidOperationException` ("Failed to convert configuration value 'abc' at 'Mail:Port' to type 'System.Int32'"). - **Nested objects, arrays and dictionaries** bind recursively from child sections. ## When binding happens Registration only records what to do. The options factory creates and binds the object the first time something reads `.Value` (or `Get(name)`). Two consequences: 1. A conversion error or a missing required value surfaces on the first request that needs mail, not at startup, unless startup validation forces the read. 2. Values captured in a constructor (`_mail = options.Value`) are a snapshot; `IOptions<T>` itself never recomputes. ## Two related tools - **Startup-only reads.** `builder.Configuration.GetSection("Mail").Get<MailOptions>()` binds a new object immediately, without DI. It suits values needed while `Program.cs` is still registering services; it is not injectable and never reloads. - **Unit tests.** `Options.Create(new MailOptions { SmtpHost = "localhost", Port = 2525 })` returns an `IOptions<MailOptions>` wrapping that instance, so a test can construct `OrderMailer` without any configuration at all. ## What changed in .NET 10 Before .NET 10 the binder treated a configuration `null` as "no value" and the JSON provider turned `null` into an empty string. Since .NET 10 an explicit `"FromAddress": null` binds `null` over the initializer, `null` elements in arrays bind as `null`, and an empty JSON array binds as an empty array instead of being skipped. Code that relied on initializers surviving a JSON `null` needs a second look after an upgrade. ## Interview checklist - Show both registrations and say which returns an `OptionsBuilder`. - Inject `IOptions<T>` and read `.Value`. - State the binder rules: case-insensitive names, settable properties, missing keys keep defaults. - Say binding is lazy and name the .NET 10 null change.

  • Why does injecting MailOptions directly into a constructor fail when only Configure<MailOptions> was called?
    `Configure<T>` registers configuration actions for the options system, which exposes the result through `IOptions<T>`, `IOptionsSnapshot<T>` and `IOptionsMonitor<T>`. Nothing registers `MailOptions` as a service, so the container cannot resolve it unless you add something like `AddSingleton(sp => sp.GetRequiredService<IOptions<MailOptions>>().Value)`.
  • What happens when appsettings.json has "Port": "abc" for an int property?
    Nothing at registration. The first `.Value` read runs the binder, the int converter fails and the binder throws `InvalidOperationException` naming the value, the path `Mail:Port` and the target type. Chaining `ValidateOnStart()` makes that read happen during startup, so the app fails before serving requests.
  • How do you make the binder reject keys that MailOptions has no property for?
    Pass a binder callback: `BindConfiguration("Mail", o => o.ErrorOnUnknownConfiguration = true)` or the `Configure<T>(section, configureBinder)` overload. Unknown keys then throw `InvalidOperationException` instead of being ignored, which catches typos such as `SmtpHots`.

  • Configure<MailOptions> binds the section immediately when the service is registered.
  • You must register MailOptions as a singleton yourself before IOptions<MailOptions> can be injected.
  • Configuration keys must match property names with exact casing.
  • A key with no matching property makes binding fail by default.
  • A missing key resets the property to its type's default, overwriting the initializer.

Assumes ASP.NET Core 10 on .NET 10; since .NET 10 the configuration binder binds explicit null values and empty arrays instead of skipping them.

open as a page

In ASP.NET Core, how do IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T> differ in lifetime and reload behaviour, and which do you inject where?

level: middleimportance: must knowfreq 80%

basics

~20 s

IOptions<T> is a singleton computed once and never reloaded; IOptionsSnapshot<T> is scoped and recomputed per request; IOptionsMonitor<T> is a singleton whose CurrentValue updates on reload and which raises OnChange. Singletons take IOptions or IOptionsMonitor, never IOptionsSnapshot.

open as a page

In ASP.NET Core, how do ValidateDataAnnotations and ValidateOnStart make a missing payment-gateway API key fail at startup instead of on the first request?

level: middleimportance: should knowfreq 55%

basics

~20 s

ValidateDataAnnotations runs the [Required], [Range] and similar attributes when the options object is built, throwing OptionsValidationException; ValidateOnStart forces that build while the host starts, so the app refuses to start instead of failing on the first request.

open as a page

In ASP.NET Core, how do named options let one MailOptions type serve a transactional and a marketing mailer, and where does PostConfigure fit?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Register each instance with Configure<MailOptions>("Transactional", section) and Configure<MailOptions>("Marketing", section), then read IOptionsMonitor or IOptionsSnapshot .Get(name). PostConfigure actions run after all Configure actions, so they adjust or default the bound values last.

open as a page

In ASP.NET Core, when would you write an IValidateOptions<T> class or use the [OptionsValidator] source generator instead of ValidateDataAnnotations?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Write an IValidateOptions<T> when a rule spans properties or needs logic attributes cannot express; use an [OptionsValidator] partial class when you want the DataAnnotations rules checked by compile-time generated code, without reflection, for trimmed or Native AOT apps.

open as a page