Advertisement
Intermediate ASP.NET Core, Configuration & Options Pattern

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

Short answer

Named options let you register multiple configurations of the same C# options class under different string names (via Configure (name, ...)), then resolve a specific named instance using IOptionsSnapshot .Get(name) or IOptionsMonitor .Get(name) -- useful when you need several…

Save ASP.NET Core mock interview
Advertisement
AModel 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.
builder.Services.Configure<SmtpSettings>("Marketing", builder.Configuration.GetSection("Smtp:Marketing"));
builder.Services.Configure<SmtpSettings>("Transactional", builder.Configuration.GetSection("Smtp:Transactional"));

public class EmailService(IOptionsSnapshot<SmtpSettings> options) {
    public void SendMarketing() => Send(options.Get("Marketing"));
    public void SendTransactional() => Send(options.Get("Transactional"));
}
Real-world example
An application sending both marketing newsletters (via a bulk email provider) and transactional receipts (via a more reliable SMTP relay) uses named options to maintain two independently-configured SmtpSettings instances from the same class definition.
Likely follow-ups
  • How does the default (unnamed) options instance relate to named ones?
  • Can you validate each named instance independently?
Related topics