⚙️ C# / .NET Intermediate

What is options pattern in ASP.NET Core?

Answer

The Options pattern provides a type-safe way to access configuration settings in ASP.NET Core. Define a strongly typed settings class: public class EmailSettings { public string SmtpServer { get; set; } = ""; public int Port { get; set; } }. Bind in Program.cs: builder.Services.Configure<EmailSettings>(builder.Configuration.GetSection("Email"));. Inject: public EmailService(IOptions<EmailSettings> options) { var settings = options.Value; }. Three interfaces: IOptions<T>: singleton, reads config once at startup — not updated if config changes. IOptionsSnapshot<T>: scoped, re-reads config per request (hot reload in dev). IOptionsMonitor<T>: singleton with change notification — use in long-running services. Validation: use ValidateDataAnnotations() or implement IValidateOptions<T>. The options pattern is strongly preferred over injecting IConfiguration directly — provides type safety, testability, and validation.