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.
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?