Configuration Sources & Providers
Layer configuration from JSON files, environment variables, command-line args, and custom providers with priority.
Configuration Sources & Providers is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Configuration in .NET
ASP.NET Core's configuration system reads settings from multiple sources — JSON files, environment variables, command-line args, and more — and merges them into one flat key-value store accessible anywhere in your app.
appsettings.json
appsettings.json is the default configuration file. It is loaded automatically by Host.CreateApplicationBuilder. Settings are merged with environment-specific overrides.
// appsettings.json
{
"App": {
"Name": "OrderService",
"MaxRetries": 3
},
"ConnectionStrings": {
"Default": "Server=localhost;Database=orders"
}
}
// appsettings.Production.json overrides the above:
{
"ConnectionStrings": {
"Default": "Server=prod-db;Database=orders;..."
}
}Reading Configuration Values
Access configuration via IConfiguration. Keys use colon notation for nested objects. Arrays are accessed by index.
// Inject IConfiguration
public class OrderService
{
private readonly IConfiguration _config;
public OrderService(IConfiguration cfg) => _config = cfg;
public void Configure()
{
string? name = _config["App:Name"]; // "OrderService"
int maxRetries = _config.GetValue<int>("App:MaxRetries"); // 3
string? connStr = _config.GetConnectionString("Default");
// Nested section
var section = _config.GetSection("App");
string? appName = section["Name"];
}
}Environment Variables
Environment variables override JSON settings and are essential for containerized deployments. Double underscores (__) replace colon separators in nested keys.
# Set via shell or docker-compose:
export App__Name="OrderService-Prod"
export App__MaxRetries=5
export ConnectionStrings__Default="Server=prod-db;..."
// Equivalent to:
{
"App": { "Name": "OrderService-Prod", "MaxRetries": 5 },
"ConnectionStrings": { "Default": "Server=prod-db;..." }
}
// Priority: env vars > appsettings.{Environment}.json > appsettings.jsonCommand-Line Arguments
Command-line arguments have the highest priority by default. They use --key=value or --key value syntax, with colons or double-underscores for nesting.
# Override config when launching the app:
dotnet run --App:Name="CLI-Override" --App:MaxRetries=10
# Or:
dotnet run --App__Name="CLI-Override"
// The builder.Configuration.AddCommandLine() is called
// automatically by Host.CreateApplicationBuilder().
// Priority order (highest to lowest):
// 1. Command-line args
// 2. Environment variables
// 3. appsettings.{ASPNETCORE_ENVIRONMENT}.json
// 4. appsettings.jsonUser Secrets
User Secrets store sensitive config outside the project directory during development. They are never committed to source control and override appsettings.json locally.
# Initialize user secrets for the project:
dotnet user-secrets init
# Set a secret:
dotnet user-secrets set "Database:Password" "SuperSecret123"
dotnet user-secrets set "Jwt:SecretKey" "dev-only-key"
# List secrets:
dotnet user-secrets list
# Remove:
dotnet user-secrets remove "Database:Password"
# Stored in: ~/.microsoft/usersecrets/{projectId}/secrets.json
# Automatically loaded in Development environment onlyCustom Configuration Providers
Implement IConfigurationProvider and IConfigurationSource to load config from any source — database, Consul, Vault, Redis, etc.
public class DbConfigProvider : ConfigurationProvider
{
private readonly string _connStr;
public DbConfigProvider(string connStr) => _connStr = connStr;
public override void Load()
{
using var conn = new NpgsqlConnection(_connStr);
conn.Open();
using var cmd = new NpgsqlCommand(
"SELECT key, value FROM app_config", conn);
using var reader = cmd.ExecuteReader();
while (reader.Read())
Data[reader.GetString(0)] = reader.GetString(1);
}
}
public class DbConfigSource : IConfigurationSource
{
private readonly string _connStr;
public DbConfigSource(string connStr) => _connStr = connStr;
public IConfigurationProvider Build(IConfigurationBuilder b)
=> new DbConfigProvider(_connStr);
}Registering a Custom Provider
Add a custom configuration source to the builder before calling Build(). It slots into the same priority chain as built-in providers.
var builder = Host.CreateApplicationBuilder(args);
// Add custom DB config provider after appsettings.json
builder.Configuration.Add(
new DbConfigSource(
builder.Configuration.GetConnectionString("Default")!));
// Or as an extension method:
public static class ConfigExtensions
{
public static IConfigurationBuilder AddDatabaseConfig(
this IConfigurationBuilder b, string connStr)
=> b.Add(new DbConfigSource(connStr));
}
// Usage:
builder.Configuration.AddDatabaseConfig(connStr);Azure App Configuration
Azure App Configuration centralizes settings across microservices with feature flags, labels, and versioning. The official provider integrates as a standard configuration source.
// dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
// dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
builder.Configuration.AddAzureAppConfiguration(options =>
options
.Connect(builder.Configuration["AzureAppConfig:ConnectionString"])
.Select(KeyFilter.Any) // all keys
.Select(KeyFilter.Any, "Production") // label override
.UseFeatureFlags(ff =>
ff.CacheExpirationInterval = TimeSpan.FromMinutes(5))
.ConfigureRefresh(r =>
r.Register("App:Version", refreshAll: true)
.SetCacheExpiration(TimeSpan.FromMinutes(1)))
);
app.UseAzureAppConfiguration(); // enable dynamic refreshReloading Configuration
Some providers support change detection. The JSON provider can reload when the file changes. Use IOptionsMonitor<T> to react to changes at runtime.
// Enable JSON file reload on change:
builder.Configuration.AddJsonFile("appsettings.json",
optional: false, reloadOnChange: true);
// In a service, use IOptionsMonitor (not IOptions) to get live values:
public class FeatureService
{
private readonly IOptionsMonitor<FeatureFlags> _monitor;
public FeatureService(IOptionsMonitor<FeatureFlags> m) => _monitor = m;
public bool IsBetaEnabled
=> _monitor.CurrentValue.BetaEnabled; // always fresh
// React to changes:
public FeatureService(IOptionsMonitor<FeatureFlags> m)
{
_monitor = m;
m.OnChange(flags => Console.WriteLine("Config changed!"));
}
}Quick Check
What delimiter should you use to represent nested JSON configuration keys as environment variables?
Real-World: Multi-Source Config
A production setup combining appsettings, environment variables, and user secrets with explicit priority ordering.
var builder = Host.CreateApplicationBuilder(args);
// Default: appsettings.json → appsettings.{env}.json → env vars → CLI
// Add user secrets in development:
if (builder.Environment.IsDevelopment())
builder.Configuration.AddUserSecrets<Program>();
// Optionally add Azure Key Vault in production:
if (!builder.Environment.IsDevelopment())
{
var keyVaultUri = builder.Configuration["Azure:KeyVaultUri"]!;
builder.Configuration.AddAzureKeyVault(
new Uri(keyVaultUri), new DefaultAzureCredential());
}
// Now all secrets are available transparently via IConfiguration
var jwtKey = builder.Configuration["Jwt:SecretKey"]!;Recap: Configuration Sources & Providers
Key takeaways:
- Config merges from multiple sources; later sources override earlier ones
- Priority: CLI args > env vars > appsettings.{env}.json > appsettings.json
- Use
__(double underscore) in env vars for nested keys - User Secrets keep dev credentials out of source control
- Custom providers: implement
IConfigurationSource+IConfigurationProvider - Use
reloadOnChange: true+IOptionsMonitorfor live config updates
Frequently asked questions
Is the “Configuration Sources & Providers” lesson free?
Yes — the full text of “Configuration Sources & Providers” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Configuration Sources & Providers”?
Layer configuration from JSON files, environment variables, command-line args, and custom providers with priority. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Configuration Sources & Providers” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Configuration Sources & Providers
- Strongly Typed Options with IOptions
- Options Validation & Named Options
- Secrets Management