Configuration in an ASP.NET Core application often begins as a few key-value pairs: a database connection string, an external service URL, a cache duration, or a feature flag. As the application grows, reading those values through scattered string keys creates hidden coupling. Missing values may be discovered only after the first real request, and sensitive settings can accidentally end up in source control.
The Options Pattern provides a structured alternative. Related settings are represented by strongly typed classes, registered with dependency injection, and optionally validated when the application starts. The result is clearer ownership of configuration, better testability, and earlier feedback when an environment is incorrectly configured.
Why direct key access becomes fragile
Code such as configuration["Payments:TimeoutSeconds"] is convenient for a quick prototype. In a production codebase, however, it can introduce several problems:
- Key names are repeated as strings across multiple classes.
- Missing values may receive inconsistent defaults.
- Type conversion for numbers, URLs, and durations happens at runtime.
- It becomes difficult to see which component owns a group of settings.
The Options Pattern addresses these issues by placing related values behind a dedicated type. A service depends on the settings it needs rather than knowing how the configuration tree is assembled. This supports encapsulation and separation of concerns.
Create a strongly typed settings model
Assume that an external payment service has a base URL, a request timeout, and a retry limit:
{
"Payments": {
"BaseUrl": "https://payments.example.test",
"TimeoutSeconds": 10,
"MaxRetries": 3
}
}The corresponding options class can be kept small and focused:
public sealed class PaymentOptions
{
public const string SectionName = "Payments";
public string BaseUrl { get; set; } = string.Empty;
public int TimeoutSeconds { get; set; }
public int MaxRetries { get; set; }
}A section-name constant avoids repeating the literal section name throughout the application. More importantly, the class should contain only settings that belong to the same scenario. A large “everything” settings class quickly becomes another form of global state.
Register options with dependency injection
In the application startup code, bind the configuration section to the options type:
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection(PaymentOptions.SectionName));A service can now consume the typed settings through IOptions<PaymentOptions>:
using Microsoft.Extensions.Options;
public sealed class PaymentClient
{
private readonly PaymentOptions _options;
public PaymentClient(IOptions<PaymentOptions> options)
{
_options = options.Value;
}
public Uri CreateEndpoint(string path)
{
return new Uri(new Uri(_options.BaseUrl), path);
}
}The service does not need to know whether its values came from JSON, environment variables, command-line arguments, or another configuration provider. That boundary makes the component easier to test and easier to reuse.
Choosing between IOptions, IOptionsSnapshot, and IOptionsMonitor
ASP.NET Core exposes several options interfaces for different lifetime and reload requirements:
| Interface | Lifetime | Typical use |
|---|---|---|
IOptions<T> | Singleton | Settings that are treated as fixed after startup |
IOptionsSnapshot<T> | Scoped | Values recomputed for a request scope |
IOptionsMonitor<T> | Singleton | Current values and change notifications |
IOptions<T> does not provide a mechanism for reading configuration changes after the application has started. It can be injected into any service lifetime because it is registered as a singleton.
IOptionsSnapshot<T> is scoped and is designed for scoped or transient dependencies that need a snapshot for the current request scope. It supports named options as well.
IOptionsMonitor<T> is also a singleton and can be injected into singleton services. It provides access to current values, named options support, and change notifications when the underlying provider supports reload behavior.
Dynamic reload should not be enabled automatically for every setting. If a value changes while an operation is in progress, the application must still have a predictable consistency model. Reload is useful when the setting can safely change at runtime; otherwise, validating it at startup and treating it as immutable is often simpler.
Validate configuration before serving traffic
Binding alone does not guarantee that the resulting object is meaningful. A missing URL, a zero timeout, or an excessive retry count can produce failures much later than the configuration error itself.
Data annotations are suitable for basic constraints:
using System.ComponentModel.DataAnnotations;
public sealed class PaymentOptions
{
public const string SectionName = "Payments";
[Required, Url]
public string BaseUrl { get; set; } = string.Empty;
[Range(1, 120)]
public int TimeoutSeconds { get; set; }
[Range(0, 10)]
public int MaxRetries { get; set; }
}Register the options and enable validation:
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection(PaymentOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();ValidateOnStart causes validation to run during application startup instead of waiting for the first options access. This is especially useful in deployment pipelines because a bad environment can fail fast rather than appear healthy until traffic arrives.
For rules that cannot be expressed with attributes, use a custom validation delegate or implement IValidateOptions<T> in a dedicated class. Keeping complex rules outside the settings model can make them easier to test and prevents the model from becoming a mixture of data and infrastructure behavior.
Cross-property validation
Some constraints involve more than one property. For example, a long timeout might require a lower retry count to keep the worst-case request duration bounded. Such a rule can be registered explicitly:
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection(PaymentOptions.SectionName))
.Validate(options =>
options.TimeoutSeconds <= 30 || options.MaxRetries <= 3,
"MaxRetries cannot exceed 3 when the timeout is greater than 30 seconds.")
.ValidateOnStart();When these rules become numerous, a dedicated validator is usually clearer. It can return meaningful error messages and be tested independently from the application host.
Environment-specific configuration and secrets
ASP.NET Core configuration can combine several providers, including JSON files, environment variables, and command-line arguments. Provider order matters: a later provider can override a value supplied by an earlier provider for the same key.
Development secrets can be stored with the Secret Manager tool, but that store should not be treated as an encrypted production vault. Passwords, tokens, and private keys should not be committed to appsettings.json or any other source-controlled file. Production secrets should be supplied through a secure secret-management solution appropriate for the deployment environment.
Environment variables represent hierarchical keys with a double underscore:
Payments__BaseUrl=https://payments.example.com
Payments__TimeoutSeconds=15This allows the same options model to work across development, test, staging, and production without adding environment-specific branches to business code.
Practical design checklist
- Create one focused options class for each independent configuration area.
- Keep section names centralized instead of duplicating string literals.
- Validate required values and ranges before the application accepts traffic.
- Keep secrets out of source-controlled configuration files.
- Use
IOptionsMonitoronly when runtime updates are genuinely needed. - Treat options as read-only from the perspective of consuming services.
- Cover cross-property validation with automated tests.
Conclusion
The Options Pattern is more than a convenient way to map JSON into a class. It creates an explicit boundary between application code and configuration providers, makes dependencies visible, and enables invalid settings to be rejected at startup. By choosing the appropriate options interface and treating validation as part of deployment readiness, ASP.NET Core applications become easier to operate and less vulnerable to configuration drift.
0 Comments