Configuration
Mental Model
Configuration = key–value pairs from many sources, merged into one IConfiguration
Everything ends up here:
IConfiguration;
Configuration Sources
- Command-line arguments
- Environment variables
- User Secrets (Development only)
- appsettings.{Environment}.json
- appsettings.json
Common Sources (what interviewers expect)
| Source | Used for |
|---|---|
appsettings.json | defaults |
appsettings.Production.json | env overrides |
| Environment variables | secrets, deployment |
| User Secrets | local dev secrets |
| Azure Key Vault | production secrets |
| Command-line | quick overrides |
IConfiguration – MUST-KNOW APIs
You only need 4 things 👇
// Read simple value
config["Logging:LogLevel:Default"];
// Typed value
config.GetValue < int > "Port";
// Section
config.GetSection("Email");
// Connection string
config.GetConnectionString("DefaultConnection");
Hierarchical Config (JSON → Colon)
{
"Email": {
"SmtpServer": "smtp.gmail.com",
"Port": 587
}
}
Access:
config["Email:SmtpServer"];
Options Pattern
When to use?
When config has related settings
Steps (memorize this):
1. POCO
class EmailOptions {
public string SmtpServer { get; set; }
}
2. Register
services.Configure < EmailOptions > config.GetSection("Email");
3. Inject
IOptions<EmailOptions>
"Options pattern gives strongly-typed, validated configuration via DI."
Environment-Specific Config
Files:
appsettings.json
appsettings.Development.json
appsettings.Production.json
Automatically loaded based on:
ASPNETCORE_ENVIRONMENT
Overrides base config.
Environment Variables (VERY IMPORTANT)
Mapping rule
__ → :
Example:
ASPNETCORE_Logging__LogLevel__Default
↓
Logging:LogLevel:Default
Used for:
- Connection strings
- API keys
- Docker / cloud deployments
User Secrets (Dev only)
Commands:
dotnet user-secrets init
dotnet user-secrets set "ApiKey" "123"
Loaded automatically in Development.
❌ Never for production.
HttpClient (Configuration + DI topic)
Golden rule:
❌ Don't new HttpClient() ✅ Use IHttpClientFactory
services.AddHttpClient();
Why interviewers care:
- Prevents socket exhaustion
- Central config
- Works with Polly retries
Custom JSON Files (nice-to-know)
config.AddJsonFile("customsettings.json", optional: true);
Still accessed via:
IConfiguration;
Common Interview Traps ⚠️
❌ Hardcoding secrets ❌ Reading config directly everywhere ❌ Using IConfiguration instead of Options for complex settings ❌ Storing secrets in appsettings.json
"ASP.NET Core configuration is a layered key-value system built on IConfiguration. It supports multiple providers like JSON files, environment variables, user secrets, and command-line arguments, with later providers overriding earlier ones. For complex settings, we use the Options pattern to bind configuration sections to strongly-typed classes through dependency injection. Sensitive data is handled via environment variables or secret stores like User Secrets or Azure Key Vault."