Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 182 ยท Dependency Injection and Hosting

Configuration and Options

Learn .NET configuration: IConfiguration from memory and JSON, binding to classes, IOptions, IOptionsSnapshot, IOptionsMonitor, validation and environment layering.

Almost every real program has settings that should not be hard-coded: a database connection string, a timeout, the name of an email server, whether a feature is switched on. They change between your laptop, the test server and production, and some of them are secrets. .NET gives you a standard, layered system for this: configuration reads key/value settings from many places, and the options pattern turns them into strongly typed classes that you inject with dependency injection.

This lesson teaches both halves. You will read settings with IConfiguration, bind sections to classes, learn the differences between IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T>, validate settings so a bad value fails at startup and see how several sources override each other. All the packages are part of the ASP.NET Core shared framework, so every example runs in our runner. Add these usings for the examples: Microsoft.Extensions.Configuration and Microsoft.Extensions.DependencyInjection (and Microsoft.Extensions.Options where shown).

Configuration is a tree of strings

IConfiguration presents settings as a flat set of keys whose names use : as a separator, which together form a tree. Logging:LogLevel:Default is the key for a value nested three levels deep. Every value is a string (or missing); typing comes later with binding.

A ConfigurationBuilder collects one or more providers (sources) and builds the configuration. The simplest provider is an in-memory dictionary, which is also great in tests.

C# Keys, sections and indexers

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.

Missing keys give null from the indexer, not an exception. GetValue<T> converts the string to a number or boolean, and has an overload with a default for missing keys. A section (GetSection) is a view on a subtree; its Key is the last segment and its Path is the full key. Keys are case-insensitive: config["database:host"] finds the same value.

JSON, the usual file format

Most applications keep their settings in appsettings.json. The JSON provider flattens nested objects to colon keys, and arrays to numbered keys (Servers:0, Servers:1). In a real project you call AddJsonFile("appsettings.json"); our runner has no project files, so we feed JSON text through a stream, which is also handy in tests:

C# Loading JSON configuration

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.

The flattened list is the truth behind the tree: JSON objects, environment variables, command-line arguments and in-memory dictionaries all end up as the same colon-separated keys, which is why they can be mixed and overridden freely.

On your machine the equivalent read-only code is:

C#
// Read-only: needs appsettings.json next to the program (copied to the output folder).
var config = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

With WebApplication.CreateBuilder() or Host.CreateApplicationBuilder() you get all of this automatically: appsettings.json, appsettings.{Environment}.json, user secrets (in Development), environment variables and command-line arguments, in that order.

Layering: later sources win

When two providers define the same key, the provider added last wins. This is how one program runs unchanged on every machine: defaults in the base file, a different value for production in a second file, and an environment variable or command-line flag as the final override.

C# Layers and overrides

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 key came from a different layer: the server from the command line (layer 4), the port from the environment variable (layer 3), and UseTls from the production values (layer 2). Two details are worth remembering:

  • Environment variable names cannot contain : on every operating system, so use a double underscore (Mail__Port) which .NET converts to Mail:Port. The prefix parameter strips and filters, so unrelated variables like PATH stay out of your configuration.
  • In ASP.NET Core the ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT) variable names the environment (Development, Staging, Production) and decides which appsettings.{Environment}.json file is layered on top.

Never commit secrets (passwords, API keys, connection strings with passwords) to appsettings.json or source control. In development use the user secrets store (dotnet user-secrets), in production use environment variables or a secret manager such as Azure Key Vault or AWS Secrets Manager. Configuration providers make these just another layer.

Binding configuration to classes

Reading config["Database:Port"] all over the code scatters magic strings and string-to-int conversions. The better approach is to create a class that mirrors a section and bind it. The binder matches property names to keys (case-insensitively), converts types, fills nested objects, lists and dictionaries, and leaves missing properties at their defaults.

C# Bind and Get

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.

The binder understands numbers, booleans, enums, TimeSpan, Uri, lists, dictionaries and nested objects. By default it binds public settable properties; read-only or private ones are skipped unless you pass options => options.BindNonPublicProperties = true. Properties without a matching key keep whatever value the class initialized them with, so give sensible defaults in the class. An invalid value (for example Port = "abc") throws InvalidOperationException during binding.

The options pattern

Binding by hand is fine, but the platform offers a standard way to deliver the bound class to the places that need it: options. You register the section once with services.Configure<T>(section), and consumers ask for IOptions<T> (or its siblings) in their constructor. This gives you:

  • strong typing and a single place to look up what a feature can be configured with,
  • integration with DI and its lifetimes,
  • validation, post-configuration and live reloading,
  • easy tests: create Options.Create(new SmtpSettings { ... }) instead of mocking configuration.
C# IOptions in a service

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>.Value creates the object the first time you read it and then keeps it. A common convention is to put the section name in a constant on the options class (GreetingOptions.SectionName), so the registration and the class cannot drift apart.

IOptions, IOptionsSnapshot and IOptionsMonitor

There are three interfaces for reading options, and the difference is when they see changes to the configuration source (for example an edited appsettings.json with reloadOnChange: true):

Interface Lifetime Sees changes? Typical use
IOptions<T> Singleton No: value is fixed after first use Settings that never change while the app runs
IOptionsSnapshot<T> Scoped Yes, once per scope (e.g. per request) Web request code that should see fresh values on the next request
IOptionsMonitor<T> Singleton Yes, always the current value + OnChange callback Singletons and background services that must follow live changes

Because IOptionsSnapshot<T> is scoped, you cannot inject it into a singleton (that would be a captive dependency, see the DI lesson); IOptionsMonitor<T> is the one that works everywhere. The following program changes the underlying configuration while the program runs, using a small mutable provider (an in-memory source we can reload) to simulate editing a file.

C# Seeing changes with 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 still reports the old value after the change; the monitor and a snapshot created after the change both report the new one. (The OnChange callback may run on another thread and, in file-based setups, usually fires after a short debounce delay, so never depend on its exact timing or print order in real programs.) For files, AddJsonFile(..., reloadOnChange: true) plus IOptionsMonitor gives you "edit the file, running app picks it up" without a restart.

Validating options

Configuration is user input: someone will set Port to -5 or forget the host. Validate options when they are bound, so a mistake is reported with a clear message instead of failing later in a random place. The options builder (AddOptions<T>()) supports data annotation attributes, delegates and custom validators. Adding ValidateOnStart() makes the check run when the host starts, so a broken deployment fails immediately.

C# Validation with data annotations

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.

Validation runs lazily here, the first time .Value is read, and throws OptionsValidationException with every failure listed at once. In a host application you would call .ValidateOnStart() on the builder so the process refuses to start with a bad configuration, which is far better than discovering the problem when the first customer triggers that code path. For validation logic that needs services, implement IValidateOptions<T> and register it. (Using [OptionsValidator], a source generator, gives the same without reflection and is the recommended path for AOT.)

Named options and post-configuration

If you need several instances of the same options type, for example two database connections or two HTTP endpoints, use named options: services.Configure<EndpointOptions>("primary", section1) and IOptionsMonitor<T>.Get("primary"). If you need to adjust values after binding (normalize a URL, fill a derived value), use PostConfigure<T>.

C# Named options and PostConfigure

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.

Design guidelines

  • One options class per feature, bound to one section. Do not inject IConfiguration into business classes; it spreads magic strings and makes tests awkward.
  • Give defaults in the class so a missing section still produces a working object, and document the keys in a README.
  • Validate early (ValidateDataAnnotations().ValidateOnStart()).
  • Choose the right interface: IOptions<T> for fixed settings, IOptionsSnapshot<T> for per-request freshness, IOptionsMonitor<T> for singletons that must follow changes.
  • Keep secrets out of files and out of logs. Do not print whole configurations; they may contain passwords.
  • Watch for typos: a misspelled key silently gives you the default value. Get<T>(o => o.ErrorOnUnknownConfiguration = true) makes the binder throw when a section contains a key that matches no property, and a test that binds your real appsettings.json is cheap insurance.
  • Consider the binding source generator for trimmed or Native AOT apps. It replaces the reflection-based binder with generated code; you switch it on in the project file on your machine:
XML
<!-- Read-only: .csproj on your machine. Generates binding code at compile time (AOT friendly). -->
<PropertyGroup>
  <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
</PropertyGroup>

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two configuration providers define Mail:Port. Which value does the application see?

    Providers are layered in the order they are added, and later providers override earlier ones. That is how environment variables and command-line arguments override JSON files.
  2. 2. How do you write the key Mail:Port as an environment variable name?

    Colons are not allowed in environment variable names on all systems, so the double underscore is used and converted to a colon by the provider.
  3. 3. Which interface should a singleton background service use to see live changes in configuration?

    IOptionsMonitor<T> is a singleton and always returns the current value. IOptionsSnapshot<T> is scoped (so it cannot be injected into a singleton), and IOptions<T> never changes after first use.
  4. 4. What does ValidateOnStart() add to the options builder?

    Without it, validation runs the first time the options value is read. ValidateOnStart moves the failure to startup, which is much easier to notice and fix.
  5. 5. What happens when a bound class has a property with no matching key in the configuration?

    The binder only sets properties for which it finds keys. Everything else keeps its initial value, which is why sensible defaults in the class are a good habit.

Summary

  • IConfiguration exposes settings as colon-separated string keys; providers (in-memory, JSON, environment variables, command line) feed it, and later providers override earlier ones.
  • Keys are case-insensitive; arrays become numbered keys; use __ instead of : in environment variable names.
  • GetSection, GetValue<T>, Bind and Get<T> convert configuration into typed values and objects.
  • The options pattern (Configure<T>, IOptions<T>) delivers typed settings through DI and keeps classes free of magic strings.
  • IOptions<T> is fixed, IOptionsSnapshot<T> is fresh per scope, IOptionsMonitor<T> follows changes and works in singletons.
  • Validate options with data annotations, Validate(...) or IValidateOptions<T>, and use ValidateOnStart() to fail early.
  • Keep secrets out of source control: user secrets in development, environment variables or a secret manager in production.

Next: Logging