skip to content

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%

answer

  1. same type, different names
  2. Configure<T>(name, section)
  3. Get(name) on snapshot or monitor
  4. PostConfigure runs after every Configure
  5. IConfigureNamedOptions for DI-backed setup

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.

solid answer

~30 s

Named options give several independently configured instances of one class. `builder.Services.Configure<MailOptions>("Transactional", config.GetSection("Mail:Transactional"))` and the same for `"Marketing"`, or `AddOptions<MailOptions>("Marketing").BindConfiguration("Mail:Marketing")`, bind different sections under different names. Consumers call `IOptionsMonitor<MailOptions>.Get("Marketing")` or `IOptionsSnapshot<MailOptions>.Get(...)`; `IOptions<T>` only exposes the default name, which is the empty string. The factory runs configure actions in registration order, then post-configure actions, then validators; `PostConfigure` (or `PostConfigureAll` for every name) is the place for defaults and normalisation that must win over binding, such as trimming a host name. `ConfigureAll` applies to every name. When setup needs services, implement `IConfigureNamedOptions<T>` or use `OptionsBuilder.Configure<TDep>`.

code

csharp · 14 lines
csharp
builder.Services.Configure<MailOptions>("Transactional",
    builder.Configuration.GetSection("Mail:Transactional"));
builder.Services.Configure<MailOptions>("Marketing",
    builder.Configuration.GetSection("Mail:Marketing"));

// runs after both bindings, for every name
builder.Services.PostConfigureAll<MailOptions>(o =>
    o.FromAddress = o.FromAddress.ToLowerInvariant());

app.MapGet("/mail/relays", (IOptionsSnapshot<MailOptions> mail) => new
{
    tx = mail.Get("Transactional").SmtpHost,
    bulk = mail.Get("Marketing").SmtpHost,
});

go deeper

for a junior

Know that one options class can be registered several times under different names and read with Get(name).

for a middle

Explain Configure with a name, why IOptions sees only the default name, and that PostConfigure runs after all Configure actions.

for a senior

Use the factory order deliberately: normalise in PostConfigure, validate named instances at startup, and use IConfigureNamedOptions for setup that needs services.

for a principal

Choose named options versus separate classes based on whether instances truly share a shape and lifecycle, keeping configuration readable for operators.

## Why names exist The subscription-box service sends two kinds of mail: order confirmations through a reliable transactional relay and newsletters through a bulk relay. Both need the same shape of settings, so one `MailOptions` class serves both, under two **names**: ```json { "Mail": { "Transactional": { "SmtpHost": "relay-tx.internal", "Port": 587, "FromAddress": "[email protected]" }, "Marketing": { "SmtpHost": "relay-bulk.internal", "Port": 2525, "FromAddress": "[email protected]" } } } ``` ## Registering and reading named instances ```csharp builder.Services.AddOptions<MailOptions>("Transactional") .BindConfiguration("Mail:Transactional").ValidateDataAnnotations().ValidateOnStart(); builder.Services.AddOptions<MailOptions>("Marketing") .BindConfiguration("Mail:Marketing").ValidateDataAnnotations().ValidateOnStart(); public sealed class NewsletterSender(IOptionsMonitor<MailOptions> mail) { private MailOptions Settings => mail.Get("Marketing"); } ``` - The unnamed instance has the name `Options.DefaultName`, the empty string. `IOptions<T>.Value` and `IOptionsMonitor<T>.CurrentValue` read only that one. - `IOptionsSnapshot<T>.Get(name)` and `IOptionsMonitor<T>.Get(name)` read any name. A name nobody configured still returns an object: a fresh instance with only the `ConfigureAll`/`PostConfigureAll` actions applied, which usually means empty strings. - `ValidateOnStart()` on a named builder validates that name at startup. ## The order inside the factory For each name, the options factory runs a fixed pipeline: 1. Create the instance (parameterless constructor and initializers). 2. Run every `IConfigureOptions<T>` / `IConfigureNamedOptions<T>` that matches the name, **in registration order**. Binding is one of these. 3. Run every `IPostConfigureOptions<T>` that matches the name. 4. Run every `IValidateOptions<T>`; collect failures. | API | Applies to | Runs in step | |---|---|---| | `Configure<T>(action)` | Default name only | 2 | | `Configure<T>(name, action)` | That name | 2 | | `ConfigureAll<T>(action)` | Every name | 2 | | `PostConfigure<T>(action)` | Default name only | 3 | | `PostConfigure<T>(name, action)` | That name | 3 | | `PostConfigureAll<T>(action)` | Every name | 3 | Because step 2 runs in registration order, two `Configure` calls for the same name are "last one wins" by order of code. `PostConfigure` is order-independent relative to them: it always runs after every configure action, which makes it the right place for normalisation and computed defaults: ```csharp builder.Services.PostConfigureAll<MailOptions>(o => { o.SmtpHost = o.SmtpHost.Trim(); if (o.Port == 0) o.Port = 587; }); ``` Validation in step 4 sees the post-configured values, so a default filled in by `PostConfigure` satisfies a `[Range]` rule. ## Setup that needs services A lambda passed to `Configure` cannot take constructor dependencies. Two options exist: - `OptionsBuilder<T>.Configure<TDep>((o, dep) => ...)` (up to five dependencies) resolves services for the action. - A class implementing `IConfigureNamedOptions<T>` (or `IConfigureOptions<T>` for the default name) registered with `ConfigureOptions<TSetup>()`, which the container constructs with its dependencies. Both run in step 2, so their position relative to binding depends on registration order. ## Reload and typos Each named binding registers its own change-token source, so after a reload `IOptionsMonitor<T>` rebuilds the affected names and its `OnChange` listener receives the new value together with the name, letting one listener tell the transactional relay from the marketing one. Names are plain strings: `Get("Marketting")` silently returns an unconfigured instance, so keep names in constants and validate each named instance with `ValidateOnStart()`. ## Interview checklist - Named options: one type, many configured instances, read with `Get(name)`. - `IOptions<T>` sees only the default (empty) name. - Factory order: configure (in order), post-configure, validate. - `ConfigureAll`/`PostConfigureAll` for every name; `IConfigureNamedOptions<T>` for DI-backed setup.

  • What does IOptions<MailOptions>.Value return when only named instances were configured?
    The default-named instance, whose name is the empty string. No configure action targeted that name, so it is a fresh `MailOptions` with only its initializers and any `ConfigureAll`/`PostConfigureAll` actions applied. `IOptions<T>` cannot read named instances; use `IOptionsMonitor<T>.Get(name)` or `IOptionsSnapshot<T>.Get(name)`.
  • Two Configure<MailOptions> calls set FromAddress for the default name, one in a library and one in Program.cs. Which wins, and how do you guarantee yours does?
    Configure actions run in registration order, so the one registered last wins. To win regardless of order, set it in `PostConfigure<MailOptions>`, which runs after every configure action for that name.

  • IOptions<MailOptions>.Value has an overload that takes the instance name.
  • PostConfigure runs in registration order alongside the Configure actions.
  • Asking IOptionsMonitor<T>.Get for an unregistered name throws.
  • ConfigureAll applies only to named instances, not the default one.
  • Named options require a separate options class per name.