How does the ASP.NET Core configuration system layer multiple sources (appsettings.json, environment variables, command line) together?
Short answer
IConfiguration builds a unified key-value configuration tree by combining multiple providers in a specific registration order, where later-registered providers override earlier ones for the same key -- the default host builder registers appsettings.json first, then…
Advertisement
AModel answer
IConfiguration builds a unified key-value configuration tree by combining multiple providers in a specific registration order, where later-registered providers override earlier ones for the same key -- the default host builder registers appsettings.json first, then appsettings.{Environment}.json, then user secrets (development only), then environment variables, then command-line arguments, meaning environment variables and command-line args can always override file-based settings, which is essential for containerized deployments.
// Default precedence (later overrides earlier):
// appsettings.json -> appsettings.Production.json -> environment variables -> command-line args
// appsettings.json: "ConnectionStrings:Db": "local-connection"
// Environment variable ConnectionStrings__Db="prod-connection" overrides itReal-world example
A containerized application ships with a generic appsettings.json for local development, while the actual production connection string is injected via a Kubernetes-managed environment variable, overriding the file-based default without needing separate builds per environment.
Likely follow-ups
- Why does the environment variable provider use double underscores (__) instead of colons for nested keys?
- How would you add a custom configuration source, like a database provider?
Related topics