Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท .NET, Tools and Concepts

Options and configuration

Reference for .NET configuration and the options pattern: configuration sources, binding to classes, IOptions variants, validation, and dependency injection lifetimes.

.NET apps read settings through configuration: a layered set of key/value pairs collected from several providers (JSON files, environment variables, command-line arguments, user secrets, in-memory data). Later providers override earlier ones, so a default in appsettings.json can be replaced by an environment variable in production without a rebuild.

The options pattern turns a section of that configuration into a strongly typed class that you receive through dependency injection (DI). Instead of reading config["Smtp:Port"] all over the code, a service asks for IOptions<SmtpOptions> and gets an object with a real int Port.

C#
builder.Services.Configure<SmtpOptions>(builder.Configuration.GetSection("Smtp"));

Try it

The packages for configuration and DI ship with the shared framework, so they work here. An in-memory provider stands in for appsettings.json.

C# Layered configuration and binding

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.

Options become useful together with the DI container. Here a service receives IOptions<T>, and a validation rule rejects a bad configuration the first time the value is read.

C# Options with DI and validation

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.

Syntax

C#
IServiceCollection Configure<TOptions>(this IServiceCollection services, IConfiguration config) where TOptions : class;
OptionsBuilder<TOptions> AddOptions<TOptions>(this IServiceCollection services) where TOptions : class;
// OptionsBuilder: Bind, Configure, Validate, ValidateDataAnnotations, ValidateOnStart

Default sources of WebApplication.CreateBuilder() and Host.CreateApplicationBuilder(), lowest priority first:

Order Source Notes
1 appsettings.json Checked-in defaults.
2 appsettings.{Environment}.json Environment-specific overrides.
3 User secrets Development only; keeps passwords out of the repository.
4 Environment variables Smtp__Port=587 (double underscore for :).
5 Command-line arguments --Smtp:Port=587.

The three option interfaces:

Interface Lifetime Sees changes at runtime?
IOptions<T> Singleton, computed once. No.
IOptionsSnapshot<T> Scoped (once per request). Yes, between requests.
IOptionsMonitor<T> Singleton. Yes, immediately; has OnChange.

Service lifetimes:

Method Instance is created
AddSingleton Once, for the container's lifetime.
AddScoped Once per scope (per HTTP request in ASP.NET Core).
AddTransient Every time it is requested.

Errors: GetRequiredService throws InvalidOperationException when a service is not registered. A failed validation throws OptionsValidationException. Binding a value that cannot convert ("abc" to int) throws InvalidOperationException during Get<T>() or Bind.

Usage notes

  • All raw values are strings. config["Smtp:Port"] returns "587"; binding or GetValue<T> converts them. Use a typed class so conversion errors surface in one place.
  • Hierarchy uses a colon. Smtp:Host is the key Host in the Smtp section. Arrays are indexed: Servers:0, Servers:1.
  • Secrets never belong in appsettings.json. Use user secrets locally and environment variables or a secret store in production.
  • Validate at startup. ValidateOnStart() makes the app fail immediately on bad settings instead of on the first request that uses them.
  • Do not inject IConfiguration everywhere. It couples code to key strings. Prefer options classes.
  • Captive dependency: a singleton that takes a scoped service keeps the first instance forever. ASP.NET Core in Development validates scopes and throws to catch this.
  • Disposal: the container disposes the IDisposable services it created. Instances you register yourself (AddSingleton(instance)) are yours to dispose.
  • Constructor injection is the default style. Resolving from the provider by hand (GetRequiredService) in application code is the "service locator" pattern and hides dependencies.