Skip to main content

Configuration

Mental Model

Configuration = key–value pairs from many sources, merged into one IConfiguration

Everything ends up here:

IConfiguration;

Configuration Sources

  1. Command-line arguments
  2. Environment variables
  3. User Secrets (Development only)
  4. appsettings.{Environment}.json
  5. appsettings.json

Common Sources (what interviewers expect)

SourceUsed for
appsettings.jsondefaults
appsettings.Production.jsonenv overrides
Environment variablessecrets, deployment
User Secretslocal dev secrets
Azure Key Vaultproduction secrets
Command-linequick 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."