Search code examples
c#.net-coreasp.net-core-hosted-servicesaspnetcore-environment

How to set ASPNETCORE_ENVIRONMENT for console application?


I have the following simple console application that contains a hosted service:

    public static async Task Main(string[] args)
    {
        using (var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                // db context
                services.AddEntityFrameworkNpgsql()
                    .AddDbContext<ApplicationDbContext>();

                // hosted services
                services.AddHostedService<ConsumeScopedServiceHostedService>();
                services.AddScoped<ProcessManuallySendings>();

                // services
                services.AddHttpClient<ISendPushService, SendPushService>(x
                    =>
                {
                    x.Timeout = TimeSpan.FromSeconds(65);
                });
            })
            .Build())
        {
            // Start the host
            await host.StartAsync();

            // Wait for the host to shutdown
            await host.WaitForShutdownAsync();
        }
    }
}

It works with my database and it means that it requires connection string. I have three appsettings.json files:

enter image description here

On the development server I will use Development environment, on the production - Production. On my local machine I'm going to use Local. It's simple. I'm going to get it with the help of ASPNETCORE_ENVIRONMENT (OS environment variable).

I use Linux and in my shell (zsh) config file I have:

enter image description here

When I type in my terminal $ echo $ASPNETCORE_ENVIRONMENT I have Local. But when I start my console application

$ dotnet run // in the project folder

It's trying to start with Production environment. See debug output:

enter image description here

So how to set environment? Why Os variable doesn't work?


Solution

  • According to the docs for .Net Core 3.0 onwards, the host configuration is provided from environment variables prefixed with DOTNET_ (for example, DOTNET_ENVIRONMENT).

    If that doesn't work, you could also try setting the environment variable in the launchSettings.json like this on your profile.

    "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "DOTNET_ENVIRONMENT" : "Development"
    }