Back to all posts
·9 min read

Configuration in ASP.NET Core: the options pattern, validation and failing fast at startup

Configuration bugs are sneaky. A deployment goes out to a new environment, the application starts without complaint, the health check turns green. An hour later the first payment request arrives, the service tries to call the external provider with an empty API key, and the user sees an error page. The problem is not in the code but in a typo in the name of an environment variable; finding that out still takes a fair amount of digging through logs.

ASP.NET Core ships almost everything you need to reduce this kind of problem: the options pattern, which binds configuration to typed classes, a validation layer for those classes, and a switch that moves validation to application startup. In this post I describe how I use these pieces together, which interface I pick in which situation, and how I test configuration.

The cost of scattered IConfiguration reads

The easiest approach at first is to inject IConfiguration wherever it is needed and read values by key:

public class PaymentClient(IConfiguration configuration, HttpClient http)
{
    public async Task ChargeAsync(Charge charge)
    {
        var apiKey = configuration["Payments:ApiKey"];
        var timeout = int.Parse(configuration["Payments:TimeoutSeconds"] ?? "30");
        // ...
    }
}

This works, but it has several problems. Key names are spread through the code as strings; one person writes Payments:ApiKey, another writes Payment:ApiKey. Values are only checked at the moment they are read, so the failure surfaces during a user request. Type conversion is done by hand everywhere, and defaults can differ from one place to the next. Finally, testing the class means setting up a fake IConfiguration, which obscures what the test is really about.

The goal is to read configuration once at the edge of the application, turn it into a typed, validated object, and hand only that object to the rest of the application.

Binding settings to a typed class

The first step of the options pattern is a plain class that represents one configuration section:

public sealed class PaymentOptions
{
    public const string SectionName = "Payments";

    public string BaseUrl { get; set; } = "";
    public string ApiKey { get; set; } = "";
    public int TimeoutSeconds { get; set; } = 30;
    public int MaxRetries { get; set; } = 3;
}

The class is then bound to its section during registration:

builder.Services
    .AddOptions<PaymentOptions>()
    .BindConfiguration(PaymentOptions.SectionName);

Now the service no longer knows any key names; it just receives the object it needs:

public class PaymentClient(IOptions<PaymentOptions> options, HttpClient http)
{
    private readonly PaymentOptions _options = options.Value;
}

Keeping the section name as a constant inside the class is a small but useful habit: the link between the binding code and the configuration file is visible in one place. Putting defaults in the class itself does the same for questions like "how many seconds is the timeout if nobody sets it?".

Don't hesitate to split a section across several classes. One big AppSettings class that carries everything makes every service depend on settings it never uses. Small options classes per service or per capability are easier both to read and to test.

Moving validation to startup

Binding does not check whether values make sense. If ApiKey is missing it is bound as an empty string; if someone writes a negative number for TimeoutSeconds, that number is accepted. So the second step is validation. For simple rules, DataAnnotations are enough:

public sealed class PaymentOptions
{
    public const string SectionName = "Payments";

    [Required, Url]
    public string BaseUrl { get; set; } = "";

    [Required, MinLength(20)]
    public string ApiKey { get; set; } = "";

    [Range(1, 120)]
    public int TimeoutSeconds { get; set; } = 30;

    [Range(0, 10)]
    public int MaxRetries { get; set; } = 3;
}
builder.Services
    .AddOptions<PaymentOptions>()
    .BindConfiguration(PaymentOptions.SectionName)
    .ValidateDataAnnotations()
    .ValidateOnStart();

The critical line here is ValidateOnStart(). Without it, validation runs the first time the options value is requested, which again means during a user request. With ValidateOnStart(), validation happens while the application starts, and if any rule is violated the application does not start at all. The error message states clearly which class, which property and which rule failed.

This can look harsh at first, but in a container environment it is exactly what you want. When the new version cannot start, the orchestrator keeps the old version running, the deployment is marked as failed, and whoever sees the error reads the cause directly. A misconfigured version that receives no traffic is a far cheaper failure than one that does.

One thing to watch with nested objects: DataAnnotations validation by default only looks at top-level properties. If you want child objects validated too, you need to say so explicitly or write a separate validation for the child. Forgetting this means rules on nested settings are silently skipped.

IValidateOptions for more complex rules

Some rules do not fit on a single property. Rules such as "in production BaseUrl must use HTTPS" or "if retries are enabled, the timeout must be at least five seconds" look at more than one value or at the environment. For these there is the IValidateOptions<T> interface:

public sealed class PaymentOptionsValidator(IHostEnvironment env)
    : IValidateOptions<PaymentOptions>
{
    public ValidateOptionsResult Validate(string? name, PaymentOptions options)
    {
        var errors = new List<string>();

        if (env.IsProduction() &&
            !options.BaseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
        {
            errors.Add("Payments:BaseUrl must use HTTPS in production.");
        }

        if (options.MaxRetries > 0 && options.TimeoutSeconds < 5)
        {
            errors.Add("TimeoutSeconds must be at least 5 when retries are enabled.");
        }

        return errors.Count == 0
            ? ValidateOptionsResult.Success
            : ValidateOptionsResult.Fail(errors);
    }
}
builder.Services.AddSingleton<IValidateOptions<PaymentOptions>, PaymentOptionsValidator>();

Because the validator is an ordinary class, it can take dependencies and be unit tested on its own. Collecting all errors into a list and returning them together also matters: stopping at the first error forces whoever fixes the configuration to restart the application several times and discover the problems one by one.

For simple rules you can also add an inline check during registration in the form .Validate(o => ..., "message"). I use that only for one-line rules; once there are several conditions, a separate validator class stays more readable.

Choosing between IOptions, IOptionsSnapshot and IOptionsMonitor

There are three interfaces for getting an options value, and the differences are their lifetime and how changes show up.

IOptions<T> is registered as a singleton and its value is computed once. Even if the configuration file changes while the application runs, the value stays the same. For most settings this is the right default: endpoints, timeouts and feature limits usually change with a deployment, and a restart happens anyway.

IOptionsSnapshot<T> is registered as scoped and recomputes its value per request scope. It gives a consistent view throughout a request while changes in the file become visible on the next request. The price is rebinding and revalidating on every request. And because it is scoped, it cannot be injected into singleton services.

IOptionsMonitor<T> is registered as a singleton, always returns the current value through CurrentValue, and lets you listen for changes through OnChange. It is meant for long-running background services and singleton components that need the current value.

A common mistake here is to read the value in the constructor and store it in a field:

public class Worker(IOptionsMonitor<PaymentOptions> monitor) : BackgroundService
{
    private readonly PaymentOptions _options = monitor.CurrentValue; // misses changes

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            var options = monitor.CurrentValue; // correct: current value on every loop
            await Task.Delay(TimeSpan.FromSeconds(options.TimeoutSeconds), ct);
        }
    }
}

Reading the value once and storing it defeats the whole point of IOptionsMonitor. If live updates are really needed, the value should be read at the moment it is used. If they are not, choosing IOptions<T> is both simpler and more honest.

One more caution about live reloading: a value that can change at runtime requires every code path that uses it to be ready for that change. Values such as a connection pool size or the base address of an already created HttpClient get baked into other objects once read, and changing the file has no visible effect. That is why I prefer to limit live updates to the few settings that are actually designed for it.

Source order, environments and secrets

ASP.NET Core reads configuration in layers from several sources. In the default order come appsettings.json, then the environment-specific appsettings.{Environment}.json, user secrets in the development environment, environment variables and command-line arguments. When the same key exists in more than one source, the one read later wins.

In practice this ordering supports a clear layout: safe defaults and structure live in appsettings.json, differences between environments go into the environment-specific file, and secrets never enter files at all but come from environment variables or a secret manager. In environment variables, hierarchy is expressed with a double underscore; for the key Payments:ApiKey the variable name is Payments__ApiKey.

This is exactly where the typo scenario from the introduction comes from. A variable named Payment__ApiKey produces no error; it simply binds to nothing. When ValidateOnStart() and a [Required] rule are used together, the situation is caught while the application starts. Validation is the cheapest insurance against the complexity of configuration sources.

Another practical suggestion: logging a summary of the effective configuration at startup, without secrets, saves a lot of time when troubleshooting. Which environment is running, which address is being called and which features are enabled are all visible in one log line. Don't forget to mask secrets here; explicitly choosing the fields to log is safer than serializing the options class and logging it as a whole.

Testing configuration

One of the nice things about the options pattern is how much easier it makes testing services. Since the service only expects IOptions<T>, there is no need to set up fake configuration in tests:

var options = Options.Create(new PaymentOptions
{
    BaseUrl = "https://payments.test",
    ApiKey = new string('x', 32),
    TimeoutSeconds = 5
});

var client = new PaymentClient(options, httpClient);

The validation rules themselves should be tested as well. Custom validators are ordinary classes and can be called directly. To exercise binding and DataAnnotations rules together, a small service collection with in-memory configuration is enough:

[Fact]
public void Missing_api_key_fails_validation()
{
    var configuration = new ConfigurationBuilder()
        .AddInMemoryCollection(new Dictionary<string, string?>
        {
            ["Payments:BaseUrl"] = "https://payments.test"
        })
        .Build();

    var services = new ServiceCollection();
    services.AddSingleton<IConfiguration>(configuration);
    services.AddOptions<PaymentOptions>()
        .BindConfiguration(PaymentOptions.SectionName)
        .ValidateDataAnnotations();

    var provider = services.BuildServiceProvider();

    var ex = Assert.Throws<OptionsValidationException>(
        () => provider.GetRequiredService<IOptions<PaymentOptions>>().Value);
    Assert.Contains("ApiKey", ex.Message);
}

On top of that, a single integration test that starts the application with the real appsettings.json and environment-specific files catches mismatches between the file structure and the classes early. When a property is renamed in the class and the file is forgotten, that test turns red.

Closing

Configuration is an input that deserves as much care as the application's code, yet it usually gets a fraction of that attention. The options pattern turns that input into a typed contract, validation writes down the rules of that contract, and ValidateOnStart() makes sure failures reach the deployment pipeline instead of the user. Add the right choice of interface and a few small tests, and a large part of the question "why doesn't it work in production?" is answered before the application even starts.