.NET › Configuration & Options

How does named options support configuring multiple distinct instances of the same options type?

Advanced

Answer

Named options let you register multiple configurations of the same C# options class under different string names (via Configure<T>(name, ...)), then resolve a specific named instance using IOptionsSnapshot<T>.Get(name) or IOptionsMonitor<T>.Get(name) -- useful when you need several independently-configured instances of the same settings shape, like multiple SMTP configurations for different notification types.
builder.Services.Configure<SmtpSettings>("Marketing", builder.Configuration.GetSection("Smtp:Marketing"));
builder.Services.Configure<SmtpSettings>("Transactional", builder.Configuration.GetSection("Smtp:Transactional"));

public class EmailService {
    public EmailService(IOptionsSnapshot<SmtpSettings> options) {
        var marketingSettings = options.Get("Marketing");
        var transactionalSettings = options.Get("Transactional");
    }
}
Real-world example An application sending both marketing newsletters (via a bulk email provider) and transactional receipts (via a different, more reliable SMTP relay) uses named options to maintain two independently-configured SmtpSettings instances from the same class definition.

Common follow-ups: How does the default (unnamed) options instance relate to named ones?;Can you validate each named instance independently?