Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the environment for a .NET Core 3.0 Worker Service?

Tags:

.net-core

Here's what I tried:

  1. I took at a glance at the source for Host.CreateDefaultBuilder and started by setting the environment variable DOTNET_Environment to "Production". That failed.
  2. So then I tried the classic ASPNETCORE_ENVIRONMENT. Nope.
  3. Then I tried adding hostsettings.json to the root of the executing project:
{
    "Environment": "Production"
}

Nada.

How in the heck do you specify a production machine in order to use the appsettings.Production.json file?

like image 859
J.D. Mallen Avatar asked Oct 06 '19 04:10

J.D. Mallen


1 Answers

Nevermind, I figured it out. I'm dumb.

First, check your Properties/launchSettings.json file for the value of "DOTNET_ENVIRONMENT". That's probably enough for most, including me.

It will, in fact, also look for a hostsettings.json file in the project root by default. It was just being overridden in my case by the launchSettings environment variable declaration.

However, if you want to use the JSON approach I mentioned in the question, but with something other than the default file name or location, you gotta call ConfigureHostConfiguration in your IHostBuilder chain and add the file explicitly.

Like so:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(
            builder =>
            {
                builder.AddJsonFile("arbitraryFileName.json");
            })
        .ConfigureServices(
            (hostContext, services) =>
            {
                services.AddHostedService<Worker>();
                services.Configure<Settings>(
                    hostContext.Configuration.GetSection("Settings"));
            });

It does indeed default to "DOTNET_" as the prefix instead of "ASPNETCORE_", so make sure both are set on your production machine/VM/service.

like image 101
J.D. Mallen Avatar answered Oct 06 '22 12:10

J.D. Mallen