Volume 2 · Chapter 5 — ASP.NET Core Enterprise Development

Configuration and Options Pattern

Goutham Mayaluri 7 min read .NETC#ASP.NET Core

5.1 Introduction

Configuration separates deployment-specific values from application code, so the same build runs unchanged in development, test, and production. ASP.NET Core layers multiple configuration sources - JSON files, environment variables, user secrets, command line, and cloud stores - into one unifiedIConfiguration, and the Options pattern binds those values into strongly-typed classes. Good configuration design (and secure secret handling) is a foundational enterprise concern - a leaked secret in a committed config file is a real, common breach.

5.2 Layered Configuration Providers

Configuration is built from ordered providers, where later providers override earlier ones. This layering is what lets a baseappsettings.jsonhold defaults, anappsettings.{Environment}.jsonoverride per environment, and environment variables or a secret store override again in production.

flowchart TB
  A["appsettings.json (defaults)"] --> Cfg["IConfiguration"]
  B["appsettings.{Environment}.json"] --> Cfg
  C["User Secrets (dev)"] --> Cfg
  D["Environment Variables"] --> Cfg
  E["Key Vault / Cloud Config"] --> Cfg
  Cfg --> App["Application (via Options)\nlater providers override earlier ones"]

5.3 The Options Pattern

Rather than reading raw string keys throughout the code, the Options pattern binds a configuration section to a typed class and injects it, giving compile-time safety, validation, and clean consumption.


public sealed class DatabaseOptions
{
    public const string Section = "Database";
    [Required] public string ConnectionString { get; set; } = "";
    public int CommandTimeoutSeconds { get; set; } = 30;
}

builder.Services.AddOptions<DatabaseOptions>()
    .Bind(builder.Configuration.GetSection(DatabaseOptions.Section))
    .ValidateDataAnnotations()      // fail fast if misconfigured
    .ValidateOnStart();

5.4 IOptions vs IOptionsSnapshot vs IOptionsMonitor

The three ways to consume options differ in when they read values, which matters when configuration can change at runtime.

Interface Behavior Use for
IOptions<T> Read once, singleton Static config that never changes at runtime
IOptionsSnapshot<T> Re-read per request (scoped) Config that can change; per-request freshness
IOptionsMonitor<T> Current value + change notifications Singletons needing live updates

5.5 Secrets Management

The cardinal rule is that secrets - connection strings, API keys, certificates - must never be committed to source control. In development use user secrets; in production use a managed secret store (Azure Key Vault) accessed via managed identity, so there is no stored credential to leak, and secrets are rotated centrally and access is audited. This is covered in depth in Volumes 8 and 9.


// Secrets come from Key Vault via managed identity - never from a committed file.
builder.Configuration.AddAzureKeyVault(
    new Uri("https://bank-kv.vault.azure.net/"),
    new DefaultAzureCredential());
Senior Interview Question

What is the difference between IOptions, IOptionsSnapshot, and IOptionsMonitor?

They differ in when they read configuration values and their lifetime, which matters when config can change at runtime.IOptions<T>is a singleton that reads the configuration once (at first access) and never changes - it’s the simplest and right choice for static configuration that is fixed for the application’s lifetime; because it’s a singleton, it can be injected anywhere including into other singletons.IOptionsSnapshot<T>is registered as scoped and recomputes the options once per request (per scope), so within a request you get a consistent value but across requests you pick up configuration changes - it’s the choice for values that can change at runtime where you want per-request freshness (and note that because it’s scoped, you cannot inject it into a singleton).IOptionsMonitor<T>is a singleton that always exposes the current value and can notify you of changes via a change callback, so it’s suited to long-lived/singleton services that need to react to live configuration updates without re-reading per request. So the decision is: useIOptionsfor static config,IOptionsSnapshotwhen config can change and you want fresh values per request in scoped/request code, andIOptionsMonitorwhen a singleton needs the current value and/or change notifications. Choosing the wrong one causes bugs like config changes not being picked up (usingIOptionswhere you needed snapshot/monitor) or a lifetime mismatch (trying to use scopedIOptionsSnapshotin a singleton).

Senior Interview Question

Why use the Options pattern instead of reading IConfiguration directly?

The Options pattern binds a configuration section to a strongly-typed class and injects it, which gives several concrete benefits over scatteringIConfiguration["Some:Key"]string lookups through the code. It provides type safety and structure: values are typed properties on a class, so you get compile-time checking, IntelliSense, and no fragile magic strings or manual parsing. It supports validation - you can validate the options (data annotations or custom validation) and, withValidateOnStart, fail fast at application startup if the configuration is missing or invalid, rather than discovering it deep in a request. It decouples consumers from the configuration system: a service depends onIOptions<MyOptions>, not onIConfigurationand specific key paths, which is cleaner, more testable (you can supply options directly in tests), and follows the interface-segregation idea that a class should depend only on the settings it needs. It also naturally supports the reload semantics (snapshot/monitor) for changing configuration. ReadingIConfigurationdirectly is fine for a one-off value at startup, but for anything a service consumes it produces untyped, unvalidated, string-keyed access spread across the codebase that breaks silently when keys or types change. So the Options pattern turns configuration into validated, typed, injectable, testable settings objects, which is why it’s the recommended way to consume configuration in ASP.NET Core.

Principal Engineer Question

How do you design configuration and secrets management for an enterprise system?

I design it around three principles: separate configuration from code, layer it per environment, and never put secrets in source control. Configuration is externalized so the same deployable artifact runs in every environment with only its configuration differing - base defaults inappsettings.json, environment overrides inappsettings.{Environment}.jsonand, more importantly for deployment, environment variables and a central configuration store, layered so the right values win per environment. Application code consumes typed, validated Options rather than raw keys, withValidateOnStartso a misconfiguration fails the deployment immediately instead of causing a runtime surprise. For secrets - connection strings, API keys, certificates - the rule is absolute: they never live in committed files or images. In development I use user secrets; in production I use a managed secret store (Azure Key Vault) accessed via managed identity, so there is no stored credential to leak, secrets are rotated centrally, and every access is audited and access-controlled. This also means enabling secret scanning in CI to catch accidental commits. For configuration that changes at runtime (feature flags, tunable settings), I use a central configuration service (Azure App Configuration) withIOptionsSnapshot/IOptionsMonitorso changes propagate without redeploying, and I version and audit configuration changes. I keep the whole scheme consistent across services (often via a shared library) so teams configure the same way, and I ensure configuration and secret access is governed and auditable for compliance. The result is that behavior is separated from deployment values, the same build runs everywhere, secrets are protected in a vault with identity-based access and rotation rather than sitting in files, and misconfiguration is caught at startup - which is both operationally flexible and secure, and is exactly what a regulated enterprise requires.

5.6 Production Scenario

A production service leaks database credentials because a developer committed a config file containing secrets. The team removes the secrets from source control and history, rotates the compromised credentials, migrates all secrets to Key Vault accessed via managed identity (so nothing sensitive is stored in code or images), and enables secret scanning in CI to prevent recurrence - turning a breach into a hardened, identity-based secret-management standard.

Chapter Revision Notes

  • Configuration layers ordered providers; later providers override earlier ones.
  • The Options pattern binds config to typed, validated classes - prefer it over raw IConfiguration.
  • IOptions (static), IOptionsSnapshot (per-request fresh), IOptionsMonitor (live updates for singletons).
  • Never commit secrets - use user secrets in dev and Key Vault via managed identity in production.
  • Validate options on start so misconfiguration fails the deployment, not a request.