In ASP.NET Core, how do you bind the Mail section of appsettings.json to a MailOptions class and inject it into a service?
answer
- the options pattern
- Configure<T>(GetSection(...)) or BindConfiguration
- IOptions<T>.Value in the constructor
- public settable properties, names match keys
- binding runs on first Value, not at registration
basics
~10 sRegister 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 sThe 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 linesvar 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
Recall Configure<T> with GetSection, injecting IOptions<T> and reading .Value, and that property names match the JSON keys.
Explain BindConfiguration versus Configure<T>, the binder's matching rules, and that binding runs lazily on the first Value read.
Make binding failures and typos surface at deploy time with ErrorOnUnknownConfiguration and startup validation, and audit the .NET 10 null-binding change on upgrade.
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.