ASP.NET Core › Configuration & Options Pattern

How do you use IHostEnvironment/IWebHostEnvironment to conditionally configure services based on the current environment?

Intermediate

Answer

IWebHostEnvironment exposes properties like EnvironmentName, IsDevelopment(), IsProduction(), and IsStaging(), letting startup code branch its configuration logic based on which environment the application is running in, resolved from the ASPNETCORE_ENVIRONMENT environment variable at host startup.
if (builder.Environment.IsDevelopment()) {
    builder.Services.AddSingleton<IEmailSender, FakeEmailSender>();  // no real emails sent locally
} else {
    builder.Services.AddSingleton<IEmailSender, SmtpEmailSender>();
}
Real-world example An application registers a fake, no-op email sender when running locally in Development (avoiding accidental real emails during testing) but wires up the real SMTP implementation for Staging and Production, all controlled by the same environment detection.

Common follow-ups: How is the environment name actually determined at startup?;How do you add support for a custom environment name beyond the standard three?