skip to content

Configuration Sources & Options

How an ASP.NET Core app layers settings from JSON files, environment variables and secret stores, then binds them to typed options. Interviewers ask which value wins and which interface to inject.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

16

In ASP.NET Core, how do you bind the Mail section of appsettings.json to a MailOptions class and inject it into a service?

level: juniorimportance: must knowfreq 74%

answer

  1. the options pattern
  2. Configure<T>(GetSection(...)) or BindConfiguration
  3. IOptions<T>.Value in the constructor
  4. public settable properties, names match keys
  5. binding runs on first Value, not at registration

basics

~10 s

Register the section with builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail")) or AddOptions<MailOptions>().BindConfiguration("Mail"), then inject IOptions<MailOptions> and read .Value. Keys bind to public settable properties by name, ignoring case.

solid answer

~30 s

The options pattern maps a configuration section onto a plain class. `builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail"))` registers a binding; `builder.Services.AddOptions<MailOptions>().BindConfiguration("Mail")` does the same, resolves `IConfiguration` from DI and returns an `OptionsBuilder<MailOptions>` you can chain validation on. A service then takes `IOptions<MailOptions>` in its constructor and reads `.Value`. The binder matches keys to public properties with setters, ignoring case; keys with no property are ignored and properties with no key keep their initializer. Binding happens when `.Value` is first read, so a value like `"Port": "abc"` throws `InvalidOperationException` there, not at registration. Since .NET 10 an explicit JSON `null` overwrites the property's initializer with `null`.

code

csharp · 11 lines
csharp
var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddScoped<OrderMailer>();

var app = builder.Build();
app.MapPost("/orders/{id}/confirm", (int id, OrderMailer mailer) =>
    mailer.SendConfirmationAsync($"customer-{id}@example.com"));
app.Run();

go deeper

for a junior

Recall Configure<T> with GetSection, injecting IOptions<T> and reading .Value, and that property names match the JSON keys.

for a middle

Explain BindConfiguration versus Configure<T>, the binder's matching rules, and that binding runs lazily on the first Value read.

for a senior

Make binding failures and typos surface at deploy time with ErrorOnUnknownConfiguration and startup validation, and audit the .NET 10 null-binding change on upgrade.

for a principal

Set a convention for settings classes, such as a SectionName constant and validation on every class, so configuration errors cannot reach production silently.

## The options pattern in one picture A subscription-box service sends order confirmations by mail. Instead of reading `Mail:SmtpHost`, `Mail:Port` and friends as strings all over the code, it binds the `Mail` section once onto a class: ```json { "Mail": { "SmtpHost": "smtp.boxes.internal", "Port": 587, "FromAddress": "[email protected]", "UseStartTls": true } } ``` ```csharp public sealed class MailOptions { public const string SectionName = "Mail"; public string SmtpHost { get; set; } = ""; public int Port { get; set; } = 25; public string FromAddress { get; set; } = ""; public bool UseStartTls { get; set; } } ``` ## Two ways to register the binding | Registration | What it gives you | |---|---| | `builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail"))` | Binds the section you pass; returns `IServiceCollection` | | `builder.Services.AddOptions<MailOptions>().BindConfiguration("Mail")` | Binds the path against the app's `IConfiguration` from DI; returns `OptionsBuilder<MailOptions>` for chaining `Validate...` calls | Both also register a change-token source, so reload-aware options interfaces notice when the underlying files change. `BindConfiguration` is the shape to prefer when you will add validation, because the builder carries the chain. ## Consuming it ```csharp public sealed class OrderMailer(IOptions<MailOptions> options) { private readonly MailOptions _mail = options.Value; public Task SendConfirmationAsync(string to) => Task.CompletedTask; // connect to _mail.SmtpHost:_mail.Port ... } ``` `IOptions<T>` is registered by the options infrastructure; you never register `MailOptions` itself. Injecting `MailOptions` directly fails to resolve unless you add that registration yourself. ## How the binder matches values The configuration binder walks the section and the class together: - **Names match case-insensitively**: `smtphost` fills `SmtpHost`. - **Public properties with a setter** are bound by default; `BinderOptions.BindNonPublicProperties` widens that to non-public setters. - **Missing keys leave the initializer**: no `Port` key means `Port` stays `25`. - **Extra keys are ignored**, unless `BinderOptions.ErrorOnUnknownConfiguration` is set, which makes them throw. - **Strings are converted** with the property type's converter; `"Port": "abc"` throws `InvalidOperationException` ("Failed to convert configuration value 'abc' at 'Mail:Port' to type 'System.Int32'"). - **Nested objects, arrays and dictionaries** bind recursively from child sections. ## When binding happens Registration only records what to do. The options factory creates and binds the object the first time something reads `.Value` (or `Get(name)`). Two consequences: 1. A conversion error or a missing required value surfaces on the first request that needs mail, not at startup, unless startup validation forces the read. 2. Values captured in a constructor (`_mail = options.Value`) are a snapshot; `IOptions<T>` itself never recomputes. ## Two related tools - **Startup-only reads.** `builder.Configuration.GetSection("Mail").Get<MailOptions>()` binds a new object immediately, without DI. It suits values needed while `Program.cs` is still registering services; it is not injectable and never reloads. - **Unit tests.** `Options.Create(new MailOptions { SmtpHost = "localhost", Port = 2525 })` returns an `IOptions<MailOptions>` wrapping that instance, so a test can construct `OrderMailer` without any configuration at all. ## What changed in .NET 10 Before .NET 10 the binder treated a configuration `null` as "no value" and the JSON provider turned `null` into an empty string. Since .NET 10 an explicit `"FromAddress": null` binds `null` over the initializer, `null` elements in arrays bind as `null`, and an empty JSON array binds as an empty array instead of being skipped. Code that relied on initializers surviving a JSON `null` needs a second look after an upgrade. ## Interview checklist - Show both registrations and say which returns an `OptionsBuilder`. - Inject `IOptions<T>` and read `.Value`. - State the binder rules: case-insensitive names, settable properties, missing keys keep defaults. - Say binding is lazy and name the .NET 10 null change.

  • Why does injecting MailOptions directly into a constructor fail when only Configure<MailOptions> was called?
    `Configure<T>` registers configuration actions for the options system, which exposes the result through `IOptions<T>`, `IOptionsSnapshot<T>` and `IOptionsMonitor<T>`. Nothing registers `MailOptions` as a service, so the container cannot resolve it unless you add something like `AddSingleton(sp => sp.GetRequiredService<IOptions<MailOptions>>().Value)`.
  • What happens when appsettings.json has "Port": "abc" for an int property?
    Nothing at registration. The first `.Value` read runs the binder, the int converter fails and the binder throws `InvalidOperationException` naming the value, the path `Mail:Port` and the target type. Chaining `ValidateOnStart()` makes that read happen during startup, so the app fails before serving requests.
  • How do you make the binder reject keys that MailOptions has no property for?
    Pass a binder callback: `BindConfiguration("Mail", o => o.ErrorOnUnknownConfiguration = true)` or the `Configure<T>(section, configureBinder)` overload. Unknown keys then throw `InvalidOperationException` instead of being ignored, which catches typos such as `SmtpHots`.

  • Configure<MailOptions> binds the section immediately when the service is registered.
  • You must register MailOptions as a singleton yourself before IOptions<MailOptions> can be injected.
  • Configuration keys must match property names with exact casing.
  • A key with no matching property makes binding fail by default.
  • A missing key resets the property to its type's default, overwriting the initializer.

Assumes ASP.NET Core 10 on .NET 10; since .NET 10 the configuration binder binds explicit null values and empty arrays instead of skipping them.

open as a page

In ASP.NET Core, how do appsettings.json and appsettings.{Environment}.json combine, and how do you read a connection string from them?

level: juniorimportance: must knowfreq 78%

basics

~10 s

ASP.NET Core loads appsettings.json, then appsettings.{Environment}.json, flattens both into colon-separated keys and lets the later file win key by key. GetConnectionString("Adoptions") reads ConnectionStrings:Adoptions from the merged result.

open as a page

With the .NET 10 SDK, how do dotnet user-secrets init and set keep a maps API key out of source control, and where is it stored?

level: juniorimportance: must knowfreq 72%

basics

~10 s

dotnet user-secrets init writes a UserSecretsId GUID into the .csproj; dotnet user-secrets set "Maps:ApiKey" stores the value in a secrets.json file under that id in the user profile, outside the repository, as unencrypted JSON.

open as a page

In ASP.NET Core, how do IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T> differ in lifetime and reload behaviour, and which do you inject where?

level: middleimportance: must knowfreq 80%

basics

~20 s

IOptions<T> is a singleton computed once and never reloaded; IOptionsSnapshot<T> is scoped and recomputed per request; IOptionsMonitor<T> is a singleton whose CurrentValue updates on reload and which raises OnChange. Singletons take IOptions or IOptionsMonitor, never IOptionsSnapshot.

open as a page

In ASP.NET Core, how does an environment variable like ConnectionStrings__Adoptions override appsettings.json, and what do the ASPNETCORE_ and DOTNET_ prefixes change?

level: middleimportance: must knowfreq 70%

basics

~20 s

WebApplication.CreateBuilder loads every environment variable after the JSON files and user secrets, turning __ into the : separator, so ConnectionStrings__Adoptions overrides ConnectionStrings:Adoptions. ASPNETCORE_ and DOTNET_ variables are also loaded with the prefix stripped, but at the bottom of the chain.

open as a page

In ASP.NET Core, how do ValidateDataAnnotations and ValidateOnStart make a missing payment-gateway API key fail at startup instead of on the first request?

level: middleimportance: should knowfreq 55%

basics

~20 s

ValidateDataAnnotations runs the [Required], [Range] and similar attributes when the options object is built, throwing OptionsValidationException; ValidateOnStart forces that build while the host starts, so the app refuses to start instead of failing on the first request.

open as a page

In ASP.NET Core, what do IConfiguration's indexer, GetSection, GetValue<T> and GetConnectionString return when a key is missing or cannot be converted?

level: middleimportance: should knowfreq 52%

basics

~20 s

The indexer and GetConnectionString return null for a missing key; GetSection returns an empty section, never null; GetValue<T> returns default(T) or the supplied default, and throws InvalidOperationException when the string cannot be converted to T.

open as a page

In ASP.NET Core, why does a key stored with dotnet user-secrets load in Development but read null in Staging, and how do you load it elsewhere?

level: middleimportance: should knowfreq 50%

basics

~10 s

WebApplication.CreateBuilder adds the user-secrets source only when the environment is Development, finding the store through the app assembly's UserSecretsIdAttribute. In Staging nothing reads secrets.json; call builder.Configuration.AddUserSecrets<Program>() where a non-Development run really needs it.

open as a page

In ASP.NET Core, how do named options let one MailOptions type serve a transactional and a marketing mailer, and where does PostConfigure fit?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Register each instance with Configure<MailOptions>("Transactional", section) and Configure<MailOptions>("Marketing", section), then read IOptionsMonitor or IOptionsSnapshot .Get(name). PostConfigure actions run after all Configure actions, so they adjust or default the bound values last.

open as a page

In ASP.NET Core, when would you write an IValidateOptions<T> class or use the [OptionsValidator] source generator instead of ValidateDataAnnotations?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Write an IValidateOptions<T> when a rule spans properties or needs logic attributes cannot express; use an [OptionsValidator] partial class when you want the DataAnnotations rules checked by compile-time generated code, without reflection, for trimmed or Native AOT apps.

open as a page

In ASP.NET Core, what sources does WebApplication.CreateBuilder load and in which order, and why might production ignore a value set in appsettings.Production.json?

level: seniorimportance: should knowfreq 58%

basics

~20 s

Later sources win: ASPNETCORE_ and DOTNET_ variables, appsettings.json, appsettings.{Environment}.json, {ApplicationName}.settings files, user secrets in Development, all environment variables, then command-line arguments. Production usually ignores a file value because a variable or argument overrides it, or the file never loads.

open as a page

In ASP.NET Core, what does reloadOnChange do for the appsettings files, which sources never reload, and how does code observe a change?

level: seniorimportance: should knowfreq 42%

basics

~20 s

With reloadOnChange, which the default builder turns on for every JSON file, a file watcher re-reads the file after a save and fires the configuration's reload token. Environment variables and command-line arguments are read once at startup and never reload.

open as a page

In ASP.NET Core 10, how do you load production secrets from Azure Key Vault with AddAzureKeyVault and DefaultAzureCredential, and what happens at startup when access fails?

level: seniorimportance: should knowfreq 52%

basics

~10 s

Reference Azure.Extensions.AspNetCore.Configuration.Secrets and Azure.Identity, then call builder.Configuration.AddAzureKeyVault(vaultUri, new DefaultAzureCredential()). The provider lists and reads every enabled secret while the source is added, so a missing credential or permission stops startup with an exception.

open as a page

With AddAzureKeyVault in ASP.NET Core, how does a secret named Maps--ApiKey become a configuration key, and how do a custom KeyVaultSecretManager and ReloadInterval change what loads?

level: seniorimportance: should knowfreq 32%

basics

~20 s

KeyVaultSecretManager.GetKey replaces -- with :, so Maps--ApiKey becomes Maps:ApiKey. A subclass can override Load to choose which secrets are fetched and GetKey to rename them; ReloadInterval, null by default, makes the provider poll for changes.

open as a page

In ASP.NET Core, how does AddKeyPerFile turn a directory of mounted secret files, such as /run/secrets, into configuration keys?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

AddKeyPerFile reads every file in a directory: the file name, with __ turned into :, becomes the key and the file content becomes the value after one trailing newline is trimmed. A file named Maps__ApiKey therefore supplies Maps:ApiKey.

open as a page

In ASP.NET Core, how do you build a custom configuration provider that loads feature switches from a database, and where does builder.Configuration.Add place it?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Write an IConfigurationSource whose Build returns a class derived from ConfigurationProvider, override Load to fill Data with colon keys, and call OnReload after a refresh. Adding it after CreateBuilder appends it last, above environment variables and arguments.

open as a page