wasAsked.

What is the Options pattern in ASP.NET Core and how do IOptions, IOptionsSnapshot and IOptionsMonitor differ?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · ASP.NET Core, .NET

Community answers

Posted by wasAsked editorial collection

The Options pattern binds configuration sections to strongly typed classes and injects them into services, instead of reading raw strings from IConfiguration everywhere. Setup appsettings.json: { "Email": { "SmtpHost": "smtp.example.com", "Port": 587, "FromAddress": "noreply@example.com" } } public sealed class EmailOptions { public const string Section = "Email"; [Required] public string SmtpHost { get; set; } = ""; [Range(1, 65535)] public int Port { get; set; } [Required, EmailAddress] public string FromAddress { get; set; } = ""; } builder.Services.AddOptions<EmailOptions>() .Bind(builder.Configuration.GetSection(EmailOptions.Section)) .ValidateDataAnnotations() .ValidateOnStart(); // fail at startup if configuration is invalid (Shorter form: builder.Services.Configure<EmailOptions>(builder.Configuration.GetSection("Email"));) Usage: public sealed class EmailSender(IOptions<EmailOptions> options) { private readonly EmailOptions _options = options.Value; } Benefits - Strong typing, IntelliSense and refactoring support. - Validation of configuration at startup. - Separation of concerns: each feature has its own options class. - Easy testing: Options.Create(new EmailOptions { ... }). The three interfaces IOptions<T> - Registered as a singleton; the value is computed once when first accessed and never changes for the application's lifetime. - Does not pick up configuration changes at runtime. - Can be injected anywhere, including singletons. - Best for settings that never change while the app runs. IOptionsSnapshot<T> - Registered as scoped; the value is recomputed once per scope (per HTTP request in ASP.NET Core). - Picks up configuration changes for new requests if the configuration source supports reloading (reloadOnChange for JSON files, Azure App Configuration with refresh). - Supports named options (snapshot.Get("Primary")). - Cannot be injected into singletons (scoped lifetime); has some per-request overhead. IOptionsMonitor<T> - Registered as a singleton; always returns the current value through CurrentValue. - Reflects configuration changes immediately and offers OnChange callbacks: monitor.OnChange(updated => _logger.LogInformation("Email settings changed")); - Supports named options (monitor.Get("Secondary")). - Can be used in singletons and background services. Comparison - Lifetime: IOptions singleton; IOptionsSnapshot scoped; IOptionsMonitor singleton. - Reload support: IOptions no; IOptionsSnapshot yes (per request); IOptionsMonitor yes (immediately). - Named options: IOptions no; IOptionsSnapshot and IOptionsMonitor yes. - Injectable into singletons: IOptions yes; IOptionsSnapshot no; IOptionsMonitor yes. - Change notifications: only IOptionsMonitor. Named options example builder.Services.Configure<StorageOptions>("Images", config.GetSection("Storage:Images")); builder.Services.Configure<StorageOptions>("Documents", config.GetSection("Storage:Documents")); var images = monitor.Get("Images"); Related features - IConfigureOptions<T> and PostConfigure for computed or default values. - IValidateOptions<T> for complex validation logic. - Source-generated validation ([OptionsValidator]) and configuration binding source generators for trimming and Native AOT. Interview summary: "The Options pattern binds configuration to typed classes with validation. IOptions is a singleton read once, IOptionsSnapshot is scoped and refreshes per request, and IOptionsMonitor is a singleton that always provides the latest value and change notifications."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics