IC Improve Code Recipes

Recipe 6.2 · C#

The Options Pattern with Validation

Problem

Typed settings help, but nothing checks them. A missing API key or a timeout of zero is only discovered when the first request that needs it fails, possibly hours after a deployment that everyone thought went fine.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: no validation, failure appears at first use.
public PaymentClient(IConfiguration config)
{
    _baseUrl = config["PaymentApi:BaseUrl"];   // null if misspelled
    _apiKey = config["PaymentApi:ApiKey"];
    _timeout = TimeSpan.FromSeconds(
        int.Parse(config["PaymentApi:TimeoutSeconds"] ?? "0"));
}

The improved recipe

Register the settings class with the options pattern, validate it with DataAnnotations plus a custom validator for rules that span properties, and validate on startup.

C#
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace ImproveCode.Configuration;

public sealed class PaymentApiOptions
{
    public const string SectionName = "PaymentApi";

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

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

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

    [Range(0, 10)]
    public int MaxRetries { get; set; } = 3;
}

public sealed class PaymentApiOptionsValidator
    : IValidateOptions<PaymentApiOptions>
{
    public ValidateOptionsResult Validate(
        string? name, PaymentApiOptions options)
    {
        if (!options.BaseUrl.StartsWith(
                "https://", StringComparison.OrdinalIgnoreCase))
        {
            return ValidateOptionsResult.Fail(
                $"{PaymentApiOptions.SectionName}:BaseUrl must use HTTPS.");
        }

        // Retries must fit inside a two-minute overall budget.
        if (options.TimeoutSeconds * (options.MaxRetries + 1) > 120)
        {
            return ValidateOptionsResult.Fail(
                "TimeoutSeconds x (MaxRetries + 1) must not exceed 120.");
        }

        return ValidateOptionsResult.Success;
    }
}

public static class PaymentApiRegistration
{
    public static IServiceCollection AddPaymentApiOptions(
        this IServiceCollection services)
    {
        services.AddOptions<PaymentApiOptions>()
            .BindConfiguration(PaymentApiOptions.SectionName)
            .ValidateDataAnnotations()
            .ValidateOnStart();

        services.AddSingleton<
            IValidateOptions<PaymentApiOptions>,
            PaymentApiOptionsValidator>();

        return services;
    }
}

public sealed class PaymentClient(IOptions<PaymentApiOptions> options)
{
    private readonly PaymentApiOptions _options = options.Value;

    public TimeSpan Timeout =>
        TimeSpan.FromSeconds(_options.TimeoutSeconds);

    public Uri BaseAddress => new(_options.BaseUrl);
}

If ApiKey is missing, the app now refuses to start and logs:

Text
Microsoft.Extensions.Options.OptionsValidationException:
DataAnnotation validation failed for 'PaymentApiOptions' members:
'ApiKey' with the error: 'The ApiKey field is required.'.

How it works

AddOptions<T>().BindConfiguration(section) tells the container how to build a PaymentApiOptions from configuration. ValidateDataAnnotations runs the attributes, and every registered IValidateOptions<T> runs after binding as well, so cross-property rules live in a plain class you can unit test.

ValidateOnStart is the line that matters most. Without it, validation runs the first time someone asks for options.Value, which might be the first payment of the day. With it, the host validates every registered options class while starting and fails the deployment immediately, with a message that names the section and the property. A failed deployment that says "PaymentApi:ApiKey is required" takes a minute to fix. A payment outage at 9 A.M. doesn't.

The consumer asks for IOptions<PaymentApiOptions> and reads .Value once. It never sees IConfiguration, and a test can pass Options.Create(new PaymentApiOptions { ... }).

There are three ways to consume options, and the choice matters:

Interface Lifetime Picks up changes
IOptions<T> Singleton No, read once
IOptionsSnapshot<T> Scoped Per request
IOptionsMonitor<T> Singleton Yes, with OnChange

Use IOptions<T> by default. Use IOptionsMonitor<T> in singletons that must react when a file or Key Vault value changes, such as a feature flag.

Variations and pitfalls

  • [Required] on a string with a string.Empty default still fails for an empty value, which is what you want. On an int, [Required] does nothing; use [Range].
  • ValidateDataAnnotations checks the top-level object only. For nested settings objects, either validate them in the custom validator or use the source-generated validator below with [ValidateObjectMembers] on the nested property.
  • .NET 8 adds a source-generated validator: a partial class marked [OptionsValidator] that implements IValidateOptions<T> with no reflection. It's useful for trimmed or AOT apps.
  • Don't inject IOptionsSnapshot<T> into a singleton. The container rejects it in Development with scope validation, and in Production you get a captured, stale value.
  • Validation messages go to the log. Never include the value of a secret in a failure message.