Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 52 ยท Dependency Injection, Configuration and Logging

Configuration and the Options Pattern

Learn how ASP.NET Core layers configuration from JSON, environment variables and the command line, and read it with IOptions, IOptionsSnapshot and IOptionsMonitor.

Hard-coding a port, a connection string or a feature flag into C# means rebuilding the app whenever it changes, and it makes it impossible to use different values on your laptop and in production. ASP.NET Core solves this with a layered configuration system: settings come from several sources, later sources override earlier ones, and your code reads them through one interface, IConfiguration.

On top of that sits the options pattern, which binds a slice of configuration to a strongly typed class and delivers it through dependency injection. The plain-.NET basics are already taught in the C# lesson on configuration and options, so this lesson concentrates on what is different in a web app: the providers that WebApplication.CreateBuilder adds for you, the order they win in, how each options interface behaves across requests and how to make a bad setting stop the app at startup instead of at 3 a.m.

What CreateBuilder sets up

builder.Configuration is already loaded with a standard stack of providers. From lowest to highest priority:

flowchart TB
    A["1. appsettings.json"] --> B["2. appsettings.{Environment}.json"]
    B --> C["3. User secrets<br/>(Development only)"]
    C --> D["4. Environment variables"]
    D --> E["5. Command-line arguments"]
    E --> F["IConfiguration<br/>the merged view"]

Each provider sits on top of the previous ones; a key found in a later provider replaces the same key from earlier providers.

Keys form a tree and use : as the separator: Logging:LogLevel:Default. Each provider spells that in its own way:

Provider How the key Demo:Title is written
JSON { "Demo": { "Title": "..." } }
Environment variable Demo__Title=... (double underscore, because : is not allowed in every shell)
Command line --Demo:Title=... or --Demo__Title=... or Demo:Title=...
In memory a dictionary entry "Demo:Title"

Key lookup is case-insensitive. Values are strings; binding converts them to numbers, booleans, enums and so on. You can add more sources yourself (AddJsonFile, AddInMemoryCollection, AddKeyPerFile, Azure Key Vault and so on) and each one goes on top of everything added before it.

This layering is the reason the same build can run anywhere: appsettings.json holds sensible defaults, the environment file adjusts for Staging or Production, secrets stay outside the repository and the deployment platform sets environment variables for the rest. Environments and secrets goes deeper into those last layers.

Watching the layers fight

The next program prepares a temporary content folder with an appsettings.json and an appsettings.Production.json, sets two environment variables and passes command-line arguments, then asks the configuration which value won for each key. The environment name defaults to Production because that is what a host uses when nothing says otherwise.

C# Precedence of configuration providers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check each line against the diagram. Title exists only in the base file, so it survives. Mode is overridden by the environment-specific file. Region is overridden by the environment variable, and Source is set in all four places and the command line wins. A key that no provider has returns null, never an exception.

When a setting "does not take effect", print the provider list (((IConfigurationRoot)builder.Configuration).Providers) or use config.GetDebugView(). It shows each key, its final value and which provider supplied it, which finds shadowing bugs quickly.

From strings to a class: the options pattern

Reading config["Smtp:Port"] all over the code base scatters magic strings and string-to-number conversions. The options pattern replaces them with a class:

C#
public sealed class SmtpOptions
{
    public const string SectionName = "Smtp";

    public string Host { get; set; } = "";
    public int Port { get; set; } = 25;
    public bool UseTls { get; set; } = true;
}

builder.Services.Configure<SmtpOptions>(builder.Configuration.GetSection(SmtpOptions.SectionName));

Consumers ask for IOptions<SmtpOptions> (or one of its cousins) and read .Value. The class is easy to test (you can new it), the settings are discoverable in one place and the binder handles the conversions. Properties need public setters (or init-only setters) for the default binder to fill them; unknown keys are ignored and missing keys leave the default value.

Three ways to read options

All three read the same configuration, but they differ in when they re-read it:

Interface Lifetime Sees changes? Use it for
IOptions<T> Singleton No, the value is created once and cached Settings that never change while running
IOptionsSnapshot<T> Scoped Yes, new value on the next request (stable within one request) Per-request code that should follow changes
IOptionsMonitor<T> Singleton Yes, always the current value, plus OnChange callbacks Singletons, background services, middleware constructors

IOptionsSnapshot<T> is scoped, so a singleton cannot take it (see captive dependencies in the previous lesson). A singleton that must follow changes uses IOptionsMonitor<T> and reads CurrentValue each time it needs it; never copy the value into a field.

Configuration can change at runtime when a provider reloads, for example a JSON file added with reloadOnChange: true, or a vault that refreshes. The example below simulates this by writing a new value into the configuration between requests. Compare how the three interfaces react.

C# IOptions, IOptionsSnapshot and IOptionsMonitor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

IOptions<T> keeps showing the first value because it was cached. The snapshot and the monitor see the new text, and the monitor also raised its change callback. (Change callbacks can fire more than once for one change, because the configuration system and the options cache both signal; make them idempotent and quick.) In a real app the trigger is a file edit or a refresh from a configuration service, not a manual reload.

Validating options on startup

Settings can be wrong: a port of 0, a missing host, a negative timeout. By default nothing checks them, and the first request to touch the value fails somewhere deep in your code. Better to fail at startup, when the person deploying can see it immediately.

Use the builder form AddOptions<T>():

  • .Bind(section) loads the values.
  • .ValidateDataAnnotations() applies attributes such as [Required] and [Range] from System.ComponentModel.DataAnnotations.
  • .Validate(predicate, message) adds a custom rule.
  • .ValidateOnStart() runs all validations when the host starts, instead of lazily at first use.

For more complex checks, implement IValidateOptions<T> and register it; it can use other services.

C# A bad setting stops the app at startup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each broken setting is reported as a readable failure, and no request is ever served with bad data. Without ValidateOnStart() the app would have started and only the first call to /smtp would have failed.

.NET also has a source generator for options validation ([OptionsValidator]) that avoids reflection and works with Native AOT. It needs the extra generated code that the single-file runner here cannot compile, so we stay with the attribute-based version.

Design habits

  • One options class per feature, bound to one section, with a SectionName constant.
  • Defaults in the class, overrides in configuration. A missing key then costs nothing.
  • Never read IConfiguration in business classes. Inject the options; the class stays testable and the key names live in one place.
  • Use IOptionsMonitor<T> in singletons, IOptionsSnapshot<T> in scoped code and IOptions<T> when you do not need changes.
  • Validate on start for anything the app cannot work without.
  • Keep secrets out of appsettings.json. Use the environment-specific layers, covered in the next lesson.
  • Do not copy CurrentValue into a field if you want to follow changes.

For the same reason, IConfiguration also feeds logging: the Logging:LogLevel section is read through the very same system.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A key appears in appsettings.json, in an environment variable and on the command line. Which value does the app see by default?

    The default order, lowest to highest, is JSON files, user secrets, environment variables, command line. The last provider wins.
  2. 2. How do you write the key Demo:Title as an environment variable name?

    A colon is not valid in all shells, so environment variables use a double underscore for the separator. The key lookup itself is case-insensitive.
  3. 3. Which options interface should a singleton service use if it must always see the latest configuration?

    IOptionsSnapshot is scoped and cannot be injected into a singleton. IOptionsMonitor is a singleton that exposes CurrentValue and OnChange.
  4. 4. What does ValidateOnStart() change?

    Without it, validation runs lazily the first time the options are resolved. With it, a bad setting fails during startup, with every failure listed.
  5. 5. IOptions<T> is injected into an endpoint. The configuration file changes while the app runs. What does the endpoint see?

    IOptions<T> reads the configuration once and keeps the result. Use IOptionsSnapshot or IOptionsMonitor to observe changes.

Summary

  • WebApplication.CreateBuilder loads appsettings.json, appsettings.{Environment}.json, user secrets (Development), environment variables and command-line arguments; later providers override earlier ones.
  • Keys form a tree with : separators (__ in environment variables) and are case-insensitive; missing keys give null.
  • The options pattern binds a configuration section to a class and injects it, so code stays typed and testable.
  • IOptions<T> is cached forever, IOptionsSnapshot<T> is fresh per request, and IOptionsMonitor<T> always gives the current value and raises OnChange.
  • Validate with data annotations or Validate(...) and call ValidateOnStart() so bad settings stop the app at startup.
  • Keep secrets out of JSON files and defaults in the class.

Next: Environments and Secrets