.NET › Generic Host
What is IHostEnvironment, and how do you use it to conditionally configure services based on the current environment?
IntermediateAnswer
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.