As the title says I have created a new .NET 5 WorkerService but when I call HostingEnvironment.IsDevelopment() it returns false even though Environment Variable ASPNETCORE_ENVIRONMENT is set to Development.
Program.cs looks like this:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostContext, builder) =>
{
if (hostContext.HostingEnvironment.IsDevelopment())
{
builder.AddUserSecrets<Program>();
}
})
.ConfigureServices((hostContext, services) =>
{
var configuration = hostContext.Configuration;
var settings = new MyAppSettings();
configuration.GetSection("MyApp").Bind(settings);
services.AddSingleton(settings);
services.AddHttpClient();
services.AddHttpClient<MyAppHttpClient>();
services.AddHostedService<Worker>();
})
.ConfigureLogging(logging =>
{
logging.AddEventLog(eventLogSettings =>
{
eventLogSettings.SourceName = "MyAppBooker";
});
});
}
Environment Variables is set under Debug properties like this:

I can confirm that Environment Variable is set correctly as well.

I'm following the guide for "Safe storage of app secrets in development" and the code is from there.
https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#access-a-secret
I have also tried to set NETCORE_ENVIRONMENT but it made no difference.
https://github.com/dotnet/aspnetcore/issues/4150
It should work given the method descriptions I think:
Checks if the current hosting environment name is Development.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.hostingenvironmentextensions.isdevelopment?view=aspnetcore-5.0
According to documentation IHostingEnvironment.EnvironmentName Property should do this:
Gets or sets the name of the environment. The host automatically sets this property to the value of the "ASPNETCORE_ENVIRONMENT" environment variable, or "environment" as specified in any other configuration source.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.ihostingenvironment.environmentname?view=aspnetcore-5.0
Given this description I do not understand why the program sets hostContext.HostingEnvironment.EnvironmentName to Production running locally in Debug.

Thanks to @Jack A. The missing link was DOTNET_ENVIRONMENT with value Development in Environment variables. The error occurred because launchSettings.json was not in Git and therefore the original Environment variable was never set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With