Introduction

Every .NET application needs configuration — connection strings, API keys, feature flags, URLs of external services. What many developers don’t realize is that .NET 8+ has a sophisticated internal configuration pipeline, where multiple providers are loaded in a specific order, and the last one to register a value wins. Understanding this order is the difference between an application that works “by luck” and one that works by design.

In this article, I will explore how WebApplication.CreateBuilder() assembles the configuration pipeline, the exact order of the Add... calls in the ConfigurationBuilder, how Docker and Podman secrets integrate with .NET without additional code, and how IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T> react to configuration changes at runtime. If you have ever had a bug caused by an environment variable that overrode your appsettings.json — or the other way around — this article will definitively clarify what happens under the hood.

💡 Tip: This article uses .NET 8+ as a reference, but the configuration pipeline has been fundamentally the same since .NET 6. The new features in .NET 8 are refinements, not structural changes.


What Happens in WebApplication.CreateBuilder()

When you call WebApplication.CreateBuilder(args), .NET internally performs a precise sequence of registrations in the ConfigurationBuilder. This is the default order of the configuration providers:

1
2
3
4
5
6
7
8
9
var builder = WebApplication.CreateBuilder(args);

// Internally, .NET 8 registers the providers in this order:
// 1. ChainedConfigurationSource  (host configuration)
// 2. appsettings.json             (reloadOnChange: true)
// 3. appsettings.{Environment}.json (reloadOnChange: true)
// 4. User Secrets                 (only in Development)
// 5. Environment Variables
// 6. Command-line arguments

ℹ️ Info: The rule is simple — the last provider to register a value overrides the previous ones. That is why environment variables win over appsettings.json, and command-line arguments win over everything.

The Complete Order and Why

OrderProviderreloadOnChangeWhen it is registered
1ChainedConfigurationSource—Configuration inherited from the host (rarely manipulated)
2appsettings.json✅ YesAlways — the application’s default values
3appsettings.{Environment}.json✅ YesAlways — overrides values per environment
4User Secrets (secrets.json)❌ NoOnly when ASPNETCORE_ENVIRONMENT=Development
5Environment Variables❌ NoAlways — system/container variables
6Command-line arguments❌ NoAlways — arguments passed via CLI

This hierarchy is intentional: safer and more specific values have priority. appsettings.json holds the defaults; the environment (Development, Staging, Production) refines them; secrets protect sensitive data in dev; and environment variables are the standard in containers.


appsettings.json and Environments

appsettings.json is the starting point — it holds the application’s default values. The environment file (appsettings.{Environment}.json) does not need to contain every key — only the ones you want to override:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// appsettings.json — default values
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "Default": "Host=localhost;Database=meudb;Username=dev;Password=dev123"
  },
  "App": {
    "NomeExibicao": "Minha Aplicação",
    "MaxItensPorPagina": 50,
    "HabilitarCache": true
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// appsettings.Production.json — overrides only what is needed
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "App": {
    "MaxItensPorPagina": 100,
    "HabilitarCache": true
  }
}

⚠️ Warning: appsettings.Production.json must never contain production connection strings or secrets. Those values must come from environment variables (containers) or key vaults (cloud). The production file only serves to adjust behaviors such as log level, pagination and flags.

How .NET Determines the Environment

The ASPNETCORE_ENVIRONMENT variable (or DOTNET_ENVIRONMENT for non-web applications) defines which appsettings.{Environment}.json will be loaded. The conventional values are:

1
2
3
4
5
6
7
8
# In development (default in Visual Studio and dotnet run)
ASPNETCORE_ENVIRONMENT=Development

# In staging
ASPNETCORE_ENVIRONMENT=Staging

# In production
ASPNETCORE_ENVIRONMENT=Production
1
2
3
4
5
6
7
// .NET uses IHostEnvironment to expose the current environment
app.MapGet("/info", (IHostEnvironment env) => new
{
    Ambiente = env.EnvironmentName,       // "Development", "Production", etc.
    IsDev = env.IsDevelopment(),
    IsProd = env.IsProduction()
});

dotnet user-secrets — Protecting Data in Development

The User Secrets mechanism solves a real problem: developers who commit appsettings.json with database connection strings, API keys or credentials. Secrets are stored outside the repository, in the operating system user’s profile.

How It Works

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Initialize secrets in the project (creates UserSecretsId in the .csproj)
dotnet user-secrets init --project src/MeuProjeto.API

# Add a secret
dotnet user-secrets set "ConnectionStrings:Default" "Host=prod-server;Database=producao;Password=S3nh@F0rt3!" --project src/MeuProjeto.API

# List all secrets
dotnet user-secrets list --project src/MeuProjeto.API

# Remove a secret
dotnet user-secrets remove "ConnectionStrings:Default" --project src/MeuProjeto.API

Where They Are Stored

Operating SystemPath
Windows%APPDATA%\Microsoft\UserSecrets\<UserSecretsId>\secrets.json
Linux/macOS~/.microsoft/usersecrets/<UserSecretsId>/secrets.json

The UserSecretsId is a GUID generated automatically in the .csproj:

1
2
3
<PropertyGroup>
  <UserSecretsId>a1b2c3d4-e5f6-7890-abcd-ef1234567890</UserSecretsId>
</PropertyGroup>

💡 Tip: secrets.json has the same format as appsettings.json. Internally, .NET registers a JsonConfigurationProvider pointing to that file — which is why any key in appsettings.json can be overridden through a secret. To understand how User Secrets integrate with EF Core Migrations in multi-layer projects, see EF Core Migrations: Multi-Project, Secrets and Scaffolding.

User Secrets DO NOT Work in Production

The User Secrets provider is registered only when the environment is Development:

1
2
3
4
5
// Internal code of WebApplicationBuilder (simplified):
if (hostEnvironment.IsDevelopment())
{
    configBuilder.AddUserSecrets(Assembly.GetExecutingAssembly(), optional: true);
}

In production, values must come from environment variables (containers), key vaults (Azure Key Vault, AWS Secrets Manager) or Docker/Podman secrets.


Environment Variables — The Standard in Containers

Environment variables are the most important provider in containerized environments. They override both appsettings.json and appsettings.{Environment}.json.

Naming Convention

.NET converts the hierarchical separator : to __ (double underscore) in environment variables:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// appsettings.json
{
  "ConnectionStrings": {
    "Default": "..."
  },
  "App": {
    "Email": {
      "SmtpHost": "smtp.mailtrap.io"
    }
  }
}
1
2
3
# Equivalent environment variable (Linux/Docker/Podman)
ConnectionStrings__Default="Host=prod-server;Database=producao;Password=S3nh@F0rt3!"
App__Email__SmtpHost="smtp.sendgrid.net"
1
2
3
4
5
6
7
8
9
# docker-compose.yml / podman-compose.yml
services:
  api:
    image: minha-api:latest
    environment:
      - ASPNETCORE_ENVIRONMENT=Production
      - ConnectionStrings__Default=Host=db;Database=producao;Password=${DB_PASSWORD}
      - App__Email__SmtpHost=smtp.sendgrid.net
      - App__MaxItensPorPagina=200

⚠️ Warning: On Linux, environment variables are case-sensitive. ConnectionStrings__Default is different from CONNECTIONSTRINGS__DEFAULT. .NET handles both correctly thanks to the Environment Variables provider, but keep the PascalCase convention with __ for consistency.

Prefix for Filtering

In shared environments, use a prefix to avoid collisions:

1
2
3
4
5
// Load only variables with the MEUAPP_ prefix
builder.Configuration.AddEnvironmentVariables(prefix: "MEUAPP_");

// MEUAPP_ConnectionStrings__Default will be mapped to ConnectionStrings:Default
// (the prefix is removed automatically)

Docker and Podman Secrets — The Secure Approach for Containers

Environment variables solve many scenarios, but they have a security limitation: they are visible through docker inspect, podman inspect, /proc/*/environ and debug logs. For truly sensitive data (database passwords, API keys, certificates), Docker and Podman offer secrets — files mounted in memory (tmpfs) inside the container.

How Secrets Work in Docker and Podman

Secrets are stored on the host and mounted as read-only files in the container, at /run/secrets/<name>:

1
2
3
4
5
# Docker — create a secret
echo "S3nh@F0rt3!Pr0duc40" | docker secret create db_password -

# Docker Compose — define secrets
echo "S3nh@F0rt3!Pr0duc40" > ./secrets/db_password.txt
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# docker-compose.yml
services:
  api:
    image: minha-api:latest
    environment:
      - ASPNETCORE_ENVIRONMENT=Production
    secrets:
      - db_password
      - api_key
    volumes:
      # alternative: mount manually
      # - ./secrets:/run/secrets:ro

secrets:
  db_password:
    file: ./secrets/db_password.txt
  api_key:
    file: ./secrets/api_key.txt
1
2
3
4
5
6
7
# Podman — create a secret
echo "S3nh@F0rt3!Pr0duc40" | podman secret create db_password -

# Podman — use the secret in the container
podman run --secret db_password -e ASPNETCORE_ENVIRONMENT=Production minha-api:latest

# The secret is available at /run/secrets/db_password inside the container

Integrating Docker/Podman Secrets with .NET

.NET does not have a native provider for /run/secrets/. The integration is done through the key-per-file provider — a configuration provider that reads each file in a directory as a key-value pair, where the file name is the key and the content is the value:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var builder = WebApplication.CreateBuilder(args);

// Register the key-per-file provider for Docker/Podman secrets
var secretsPath = "/run/secrets";
if (Directory.Exists(secretsPath))
{
    builder.Configuration.AddKeyPerFile(
        directoryPath: secretsPath,
        optional: true,
        filePrefix: "" // no prefix — uses the file name as the key
    );
}

With this configuration, a file /run/secrets/ConnectionStrings__Default with the content Host=db;Database=prod;Password=S3nh@! will be mapped to Configuration["ConnectionStrings:Default"].

ℹ️ Info: AddKeyPerFile applies the __ → : convention automatically, just like environment variables. So a file named App__Email__SmtpHost will be accessible as Configuration["App:Email:SmtpHost"].

Naming Convention for Secrets

To keep compatibility with the .NET hierarchy:

Secret (file name)Key in ConfigurationFile content
ConnectionStrings__DefaultConnectionStrings:DefaultHost=db;Database=prod;Password=S3nh@!
App__Email__SmtpHostApp:Email:SmtpHostsmtp.sendgrid.net
App__JwtSecretKeyApp:JwtSecretKeyminha-chave-jwt-super-secreta-256bits

Podman Secrets vs Docker Secrets

FeatureDocker SecretsPodman Secrets
RequirementDocker Swarm modeWorks without Swarm (rootless)
StorageRaft log (encrypted)Local directory (encryptable)
Mount/run/secrets/ (tmpfs)/run/secrets/ (tmpfs)
Visible in inspect?❌ No❌ No
Visible in /proc?❌ No❌ No
CLIdocker secret createpodman secret create
Composedocker compose with secrets:podman-compose with secrets:

💡 Tip: If your application runs on Podman rootless (as described in this blog’s deploy), prefer Podman secrets with AddKeyPerFile. They are not exposed in logs, inspect or environment variables — an extra security layer without additional complexity.


The Complete Final Order (with Docker Secrets)

When you add all the providers, including Docker/Podman secrets, the complete pipeline order becomes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
var builder = WebApplication.CreateBuilder(args);

// Providers registered automatically by .NET 8:
// 1. ChainedConfigurationSource
// 2. appsettings.json                  (reloadOnChange: true)
// 3. appsettings.{Environment}.json    (reloadOnChange: true)
// 4. User Secrets                      (only Development)
// 5. Environment Variables
// 6. Command-line arguments

// Additional provider — Docker/Podman secrets (REGISTER AFTER the defaults):
if (Directory.Exists("/run/secrets"))
    builder.Configuration.AddKeyPerFile("/run/secrets", optional: true);

// Final priority order (last one wins):
// 1.  appsettings.json               ← lowest priority
// 2.  appsettings.Production.json
// 3.  User Secrets (only Dev)
// 4.  Environment Variables
// 5.  Command-line args
// 6.  Docker/Podman Secrets           ← highest priority (if registered last)

Diagram of the .NET 8+ configuration pipeline showing the provider loading order and the override priority among appsettings, secrets, environment variables and Docker secrets

⚠️ Warning: The position where you call AddKeyPerFile defines its priority. If you want environment variables to have priority over Docker secrets, register AddKeyPerFile before AddEnvironmentVariables. The rule is always: the last one registered wins.


IOptions<T> and Its Variants

With the pipeline assembled, the next step is to consume the configuration in a typed way. .NET offers three interfaces in the Microsoft.Extensions.Options namespace, and each one behaves differently regarding lifetime and reloading:

Registering Typed Configuration

1
2
3
4
5
6
// Program.cs
builder.Services.Configure<AppConfig>(
    builder.Configuration.GetSection("App"));

builder.Services.Configure<EmailConfig>(
    builder.Configuration.GetSection("App:Email"));
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// AppConfig.cs — POCO class with no framework dependency
public sealed class AppConfig
{
    public string NomeExibicao { get; set; } = string.Empty;
    public int MaxItensPorPagina { get; set; } = 50;
    public bool HabilitarCache { get; set; }
}

public sealed class EmailConfig
{
    public string SmtpHost { get; set; } = string.Empty;
    public int SmtpPort { get; set; } = 587;
    public string SmtpUsername { get; set; } = string.Empty;
}

IOptions<T> — Singleton, No Reload

1
2
3
4
5
6
public class MeuServico(IOptions<AppConfig> options)
{
    private readonly AppConfig _config = options.Value;

    public int ObterMaxItens() => _config.MaxItensPorPagina;
}
FeatureBehavior
LifetimeSingleton (Value is computed once and cached forever)
Reloading❌ Does not reload — if appsettings.json changes, Value keeps the original value
When to useConfiguration that never changes during the application’s lifetime
Registrationservices.Configure<T>(section)

IOptionsSnapshot<T> — Scoped, Reload per Request

1
2
3
4
5
6
public class MeuServico(IOptionsSnapshot<AppConfig> options)
{
    private readonly AppConfig _config = options.Value;

    public int ObterMaxItens() => _config.MaxItensPorPagina;
}
FeatureBehavior
LifetimeScoped (new value for each HTTP request / DI scope)
Reloading✅ Reloads — if appsettings.json changes, the next request already sees the new value
When to useAPIs and web apps where configuration can change without a restart
Restriction⚠️ Cannot be injected into Singleton services
Registrationservices.Configure<T>(section) (same registration)

IOptionsMonitor<T> — Singleton with Notification

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class MeuServico : IDisposable
{
    private readonly IDisposable? _changeListener;
    private AppConfig _config;

    public MeuServico(IOptionsMonitor<AppConfig> monitor)
    {
        _config = monitor.CurrentValue;

        // Receive a notification when the configuration changes
        _changeListener = monitor.OnChange(novaConfig =>
        {
            _config = novaConfig;
            Console.WriteLine($"Config changed! MaxItens is now {novaConfig.MaxItensPorPagina}");
        });
    }

    public int ObterMaxItens() => _config.MaxItensPorPagina;

    public void Dispose() => _changeListener?.Dispose();
}
FeatureBehavior
LifetimeSingleton (can be injected into any service)
Reloading✅ Reloads — CurrentValue always returns the latest value
Notification✅ OnChange() lets you react to changes in real time
When to useSingleton services that need to react to configuration changes
Registrationservices.Configure<T>(section) (same registration)

Quick Comparison

InterfaceLifetimeReloadNotificationUse in Singleton?
IOptions<T>Singleton❌❌✅
IOptionsSnapshot<T>Scoped✅ (per request)❌❌
IOptionsMonitor<T>Singleton✅ (in real time)✅ OnChange()✅

Named Options — Multiple Instances of the Same Configuration

When you have multiple configurations of the same type (e.g., several email providers, multiple databases):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
  "EmailProviders": {
    "Transacional": {
      "SmtpHost": "smtp.sendgrid.net",
      "SmtpPort": 587
    },
    "Marketing": {
      "SmtpHost": "smtp.mailchimp.com",
      "SmtpPort": 587
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Register as Named Options
builder.Services.Configure<EmailConfig>("Transacional",
    builder.Configuration.GetSection("EmailProviders:Transacional"));
builder.Services.Configure<EmailConfig>("Marketing",
    builder.Configuration.GetSection("EmailProviders:Marketing"));

// Consume via IOptionsSnapshot (or IOptionsMonitor)
public class EmailService(IOptionsSnapshot<EmailConfig> options)
{
    public void EnviarTransacional(string para, string assunto)
    {
        var config = options.Get("Transacional");
        // uses config.SmtpHost, config.SmtpPort...
    }

    public void EnviarMarketing(string para, string assunto)
    {
        var config = options.Get("Marketing");
        // uses config.SmtpHost, config.SmtpPort...
    }
}

Configuration Validation at Startup

A common mistake is for the application to start with invalid configuration (empty connection string, zero port) and only fail when the first request arrives. .NET 8 lets you validate at startup:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
builder.Services.AddOptions<AppConfig>()
    .Bind(builder.Configuration.GetSection("App"))
    .ValidateDataAnnotations()       // validates [Required], [Range], etc.
    .ValidateOnStart();              // fails IMMEDIATELY if invalid

builder.Services.AddOptions<EmailConfig>()
    .Bind(builder.Configuration.GetSection("App:Email"))
    .Validate(config =>
    {
        // Custom validation
        return !string.IsNullOrWhiteSpace(config.SmtpHost)
            && config.SmtpPort > 0;
    }, "SmtpHost must be filled in and SmtpPort must be greater than zero")
    .ValidateOnStart();
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// AppConfig.cs with Data Annotations for validation (not for ORM!)
using System.ComponentModel.DataAnnotations;

public sealed class AppConfig
{
    [Required(ErrorMessage = "NomeExibicao is required")]
    public string NomeExibicao { get; set; } = string.Empty;

    [Range(1, 500, ErrorMessage = "MaxItensPorPagina must be between 1 and 500")]
    public int MaxItensPorPagina { get; set; } = 50;

    public bool HabilitarCache { get; set; }
}

ℹ️ Info: ValidateOnStart() makes the application fail fast if the configuration is invalid — instead of failing mysteriously on the first request. This is especially important in containers, where a fast startup with a clear error is better than a “running” container that fails on every request.


When .NET Reloads Configuration Automatically

Not every provider supports automatic reload. Knowing which ones reload (and which don’t) avoids subtle bugs:

Providers with reloadOnChange: true

File-based providers are the only ones that support automatic reloading:

1
2
3
4
5
// WebApplicationBuilder registers with reloadOnChange: true by default:
configBuilder.AddJsonFile("appsettings.json",
    optional: true, reloadOnChange: true);
configBuilder.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
    optional: true, reloadOnChange: true);

When you edit appsettings.json or appsettings.Production.json while the application is running, .NET:

  1. Detects the change via FileSystemWatcher
  2. Reloads the affected configuration provider
  3. Emits a change token (IChangeToken)
  4. IOptionsSnapshot<T> will return the new value on the next request
  5. IOptionsMonitor<T> fires the OnChange() callback immediately
  6. IOptions<T> is not affected — it keeps the original value

Providers That DO NOT Reload

ProviderReloads?Reason
appsettings.json✅reloadOnChange: true (default)
appsettings.{Env}.json✅reloadOnChange: true (default)
User Secrets (secrets.json)❌Registered without reloadOnChange
Environment Variables❌Variables are read at startup and cached
Command-line args❌Passed once at startup
AddKeyPerFile (Docker secrets)❌Read at startup (file in tmpfs)

Forcing Reload with reloadOnChange

If you need other JSON files to reload as well:

1
2
3
4
5
6
// Add a custom JSON file WITH reloadOnChange
builder.Configuration.AddJsonFile(
    path: "config/feature-flags.json",
    optional: true,
    reloadOnChange: true   // ← enables the FileSystemWatcher
);

⚠️ Warning: In Docker/Podman containers, reloadOnChange with FileSystemWatcher may not work depending on the type of mounted volume. bind mount volumes usually work, but named volumes (docker volume) or tmpfs may not emit the necessary filesystem events. Always test in your specific scenario.


Customizing the Configuration Pipeline

When the default providers are not enough, you can customize the pipeline completely:

Adding Custom Providers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
var builder = WebApplication.CreateBuilder(args);

// The default providers were already registered by CreateBuilder.
// Everything you add below will have HIGHER priority:

// Provider for Azure Key Vault
builder.Configuration.AddAzureKeyVault(
    new Uri("https://meu-vault.vault.azure.net/"),
    new DefaultAzureCredential());

// Provider for AWS Secrets Manager
builder.Configuration.AddSecretsManager(region: RegionEndpoint.SAEast1);

// Provider for HashiCorp Vault
builder.Configuration.AddVaultConfiguration(
    () => new VaultOptions { Address = "https://vault.meudominio.com" },
    "meuapp");

// Provider for Docker/Podman secrets
if (Directory.Exists("/run/secrets"))
    builder.Configuration.AddKeyPerFile("/run/secrets", optional: true);

Replacing the Pipeline Completely

In rare scenarios where you need to control 100% of the order:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    // DO NOT load appsettings.json automatically
    // (Careful: you lose ALL default providers)
});

// Clear and rebuild manually
builder.Configuration.Sources.Clear();

builder.Configuration
    .AddJsonFile("config/base.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"config/base.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables(prefix: "MEUAPP_")
    .AddCommandLine(args);

if (builder.Environment.IsDevelopment())
    builder.Configuration.AddUserSecrets<Program>();

if (Directory.Exists("/run/secrets"))
    builder.Configuration.AddKeyPerFile("/run/secrets", optional: true);

Tips and Good Practices

  1. Never commit secrets in appsettings.json — use dotnet user-secrets in development and environment variables or Docker/Podman secrets in production. If a secret leaks into Git, consider it compromised immediately.

  2. Use ValidateOnStart() for all critical configuration — connection strings, API keys, service URLs. Failing at startup is always better than failing on the first request at 3 a.m.

  3. Prefer IOptionsMonitor<T> in Singleton services — if the service needs to react to configuration changes. Use IOptionsSnapshot<T> only in Scoped services (controllers, per-request services).

  4. Name your container secrets with __ — use ConnectionStrings__Default as the secret file name to keep compatibility with the .NET configuration hierarchy.

  5. Be careful with reloadOnChange in containers — FileSystemWatcher may not work with every volume type. Test the behavior in your environment before relying on automatic reload.

  6. Use a prefix for shared environment variables — builder.Configuration.AddEnvironmentVariables(prefix: "MEUAPP_") avoids collisions with system variables and with other services on the same host.

  7. Don’t mix configuration and code — the configuration POCO class should be simple (getters/setters). Business logic based on configuration belongs in the service that consumes IOptions<T>, never in the configuration class.

  8. Document the order of your pipeline — in projects with many providers (Key Vault, Feature Flags, Docker secrets), explicitly document the priority order for the team.


Conclusion

The .NET 8+ configuration pipeline is a powerful and extensible system that follows a simple rule: the last registered provider wins. Understanding this order — from appsettings.json (lowest priority) to Docker/Podman secrets or command-line arguments (highest priority) — is fundamental to avoiding subtle configuration bugs that only show up in production.

The trio IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T> covers every consumption scenario: static configuration (Singleton), per-request configuration (Scoped) and reactive configuration with notification (Singleton with reload). Combined with ValidateOnStart(), it ensures your application fails fast with a clear message, instead of failing mysteriously at runtime.

For Docker and Podman containers, AddKeyPerFile("/run/secrets") is the bridge between the container engine’s secrets and the .NET configuration system — secure, simple and without dependency on external packages. This fits perfectly with a deploy architecture using Podman rootless and secrets managed through a pipeline.

The natural next step is to ensure your domain entities and data access are equally decoupled — and for that, EF Core 8 with Fluent API is the ideal complement to this article.


Read Also


References