Options and configuration
Options and configuration
Configuration collects settings from sources such as JSON, environment variables and command-line arguments. A key is a path such as Worker:TimeoutSeconds. Providers added later override earlier values for matching keys. The options pattern binds related settings to a typed class and can validate the result before the application uses it.
Proposed baseline: .NET SDK 10.0.404, net10.0 / C# 14. Requires installed ASP.NET Core 10 shared framework/reference pack (FrameworkReference Microsoft.AspNetCore.App); the examples are console programs, not web servers. C# results are reasoned, not executed. See the accompanying independent project fixture; approve dependencies and environment before restoring or building.
Override a setting
Two in-memory dictionaries represent a base layer and an override; no environment variables are read.
using System;using System.Collections.Generic;using Microsoft.Extensions.Configuration;var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string?> { ["Worker:TimeoutSeconds"] = "15", ["Worker:Mode"] = "safe" }) .AddInMemoryCollection(new Dictionary<string, string?> { ["Worker:TimeoutSeconds"] = "30" }) .Build();Console.WriteLine(config["Worker:TimeoutSeconds"]);Console.WriteLine(config["Worker:Mode"]);The second provider supplies the timeout only. The mode still comes from the first provider. Override is per key, not replacement of the entire section.
Expected observation (reasoned, not executed):
30safeBind and validate typed options
The allowed timeout is 1 through 60 seconds; zero or a missing key leaves an invalid default.
using System;using System.Collections.Generic;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Options;var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>{ ["Worker:TimeoutSeconds"] = "20" }).Build();var services = new ServiceCollection();services.AddOptions<WorkerOptions>().Bind(config.GetSection("Worker")) .Validate(o => o.TimeoutSeconds is >= 1 and <= 60, "Timeout must be 1-60 seconds");using var root = services.BuildServiceProvider();Console.WriteLine(root.GetRequiredService<IOptions<WorkerOptions>>().Value.TimeoutSeconds);public sealed class WorkerOptions { public int TimeoutSeconds { get; set; } }Binding converts the supplied string to an int; the validation predicate checks the domain rule when the options value is created.
Expected observation (reasoned, not executed):
20Fail before starting work
The Generic Host can run startup validation. Disable default sources to avoid reading machine-specific settings; no hosted services or listener are registered.
using System;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Options;var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });builder.Services.AddOptions<WorkerOptions>() .Configure(o => o.TimeoutSeconds = 0) .Validate(o => o.TimeoutSeconds is >= 1 and <= 60, "Invalid timeout") .ValidateOnStart();using var host = builder.Build();try { await host.StartAsync(); await host.StopAsync(); }catch (OptionsValidationException) { Console.WriteLine("Startup rejected"); }public sealed class WorkerOptions { public int TimeoutSeconds { get; set; } }Building the host is not the same as starting it. Startup validation is triggered by StartAsync, before ordinary hosted work is started.
Expected observation (reasoned, not executed):
Startup rejectedCommon mistakes and edge cases
Default host configuration typically layers appsettings.json, environment-specific JSON, development user secrets when configured, environment variables and arguments. Environment keys use __ for nested sections (Worker__TimeoutSeconds). Explicit builders can differ. IOptions<T> gives a cached default value, IOptionsSnapshot<T> is scoped and recalculates per scope, and IOptionsMonitor<T> can observe supported reloads and is suitable for singleton consumers. Validation is not a guarantee of valid external service credentials. Never commit secrets; development user-secrets is not an encrypted production vault. Avoid dumping configuration or exception contents with secret values.
Practice and recap
A base timeout is 25, an override sets 90, and the domain permits 1–60. Predict the effective value and design a startup check. Add tests for 1, 60 and missing.
Hint: Apply provider order first.
Learning objective: Validate required settings before use. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Options and configuration — knowledge check
Apply the lesson concepts to the following scenarios.
Which matching value wins in this explicit builder?
What represents Worker:TimeoutSeconds in environment variables?
What does ValidateOnStart require to trigger startup validation?
Which options service is scoped?
Why avoid logging configuration wholesale?