Back to results for “Generic Host”
.NET › Generic Host

What is IHostEnvironment, and how do you use it to conditionally configure services based on the current environment?

Intermediate

Answer

IHostEnvironment (and its web-specific extension IWebHostEnvironment) exposes properties like EnvironmentName, IsDevelopment(), IsProduction(), and IsStaging(), letting startup code branch its configuration logic based on which environment the application is currently running in -- resolved from the ASPNETCORE_ENVIRONMENT or DOTNET_ENVIRONMENT environment variable at host startup.
var builder = Host.CreateApplicationBuilder(args);

if (builder.Environment.IsDevelopment()) {
    builder.Services.AddSingleton<IEmailSender, FakeEmailSender>();  // no real emails sent locally
} else {
    builder.Services.AddSingleton<IEmailSender, SmtpEmailSender>();
}
Real-world example A Worker Service 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 environments, 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?