C# Interview Question #165

What is the Options Pattern in ASP.NET Core?

ASP.NET Core, DI & Middleware Senior Advanced

Quick Interview Answer

The Options Pattern maps configuration sections to strongly typed C# classes.

Detailed Explanation

The Options Pattern maps configuration sections to strongly typed C# classes.

Common interfaces include IOptions<T>, IOptionsSnapshot<T>, and IOptionsMonitor<T>. IOptions<T> provides a configured value, IOptionsSnapshot<T> is scoped and can provide updated configuration per request in supported scenarios, and IOptionsMonitor<T> supports change notifications and updated values for long-lived services.

Options can also be validated during application startup so invalid configuration fails early rather than causing failures later during requests.

Code Example

builder.Services
    .AddOptions<ApiOptions>()
    .Bind(builder.Configuration.GetSection("Api"))
    .ValidateDataAnnotations()
    .ValidateOnStart();