ASP.NET Core Interview Question #30

What is the Options pattern in ASP.NET Core?

Application Structure & Configuration Junior Beginner

Quick Interview Answer

The Options pattern binds a related group of configuration settings to a strongly typed class. It avoids repeatedly using string configuration keys and makes settings easier to validate, test, and inject.

Detailed Explanation

The Options pattern binds a related group of configuration settings to a strongly typed class. It avoids repeatedly using string configuration keys and makes settings easier to validate, test, and inject.

A POCO class represents the settings, configuration is bound with Configure<TOptions>(), and consumers request IOptions<T>, IOptionsSnapshot<T>, or IOptionsMonitor<T> depending on their lifetime and reload requirements.

This pattern is preferred when an application has a coherent configuration section such as EmailSettings, JwtSettings, or PaymentSettings.

Code Example

public class EmailSettings
{
    public string Sender { get; set; } = string.Empty;
    public int Port { get; set; }
}

// Program.cs
builder.Services.Configure<EmailSettings>(
    builder.Configuration.GetSection("EmailSettings"));

public class EmailService
{
    private readonly EmailSettings _settings;

    public EmailService(IOptions<EmailSettings> options)
    {
        _settings = options.Value;
    }
}