Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set hosting environment name for .NET Core console app using Generic Host (HostBuilder)

Tags:

c#

.net-core

I am setting up a .NET Core 2.x console app as a Windows service and need to load an appsettings json file based on the environment. I was thinking to start the service with a command line argument that identifies the environment. How can I do that in Visual Studio? No matter what I set in the project settings, the EnvironmentName value is always "Production".

How can I set my environment from a command line argument?

var hostBuilder = new HostBuilder()
                 .UseContentRoot(Directory.GetCurrentDirectory())
                 .ConfigureAppConfiguration((hostingContext, config) =>
                 {
                     var env = hostingContext.HostingEnvironment;
                     config.AddCommandLine(args);
                     config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);
                     config.AddEnvironmentVariables();
                 })
                 .ConfigureServices((hostContext, services) =>
                 {
                     //Inject additional services as needed
                     services.AddHostedService<JobRunner>();
                });

enter image description here

like image 617
bitshift Avatar asked Sep 25 '19 19:09

bitshift


People also ask

What is a generic host in .NET Core?

The Generic Host can be used with other types of . NET applications, such as Console apps. A host is an object that encapsulates an app's resources and lifetime functionality, such as: Dependency injection (DI) Logging.

What is Hostbuilder in .NET Core?

Host Builder is a static class that provides two methods and when we call these methods, they will add some features into ASP.NET Core Applications. The Host Builder Provides two convenient methods for creating instances of IHostBuilder with pre-configured defaults.

What is Generic host and Web Host?

As name suggests Web host can be used only for HTTP (eg tied for web application) only but generic host, which has been introduced in . Net core 3.0, can be used for Console application as well. Though the Generic host got included in . NET core 2.1 it was only used for non HTTP workloads.

What is generic host in NET Core?

A new option available to developers working with .NET Core 2.1 is the new “generic” Host which enables developers to easily set up cross-cutting concerns such as logging, configuration and dependency injection for non-web focused applications.

Can I use a generic host in a console app?

For information on using .NET Generic Host in console apps, see .NET Generic Host. A host is an object that encapsulates an app's resources, such as: Dependency injection (DI) When a host starts, it calls IHostedService.StartAsync on each implementation of IHostedService registered in the service container's collection of hosted services.

How do I host a console application on DotNet?

dotnet new console dotnet add package Microsoft.Extensions.Hosting Now for the Main method. Typically the Main method for console apps just immediately jump into the application’s core logic, but when using the .NET Generic Host, instead the host is set up.

Where to create a DotNet generic host bug?

Dependency injection in .NET Logging in .NET Configuration in .NET Worker Services in .NET ASP.NET Core Web Host Generic host bugs should be created in the github.com/dotnet/extensionsrepo Feedback Submit and view feedback for


Video Answer


3 Answers

You can set the environment from the command line variables via the ConfigureHostConfiguration extension method.

Set up the configuration for the builder itself. This will be used to initialize the Microsoft.Extensions.Hosting.IHostEnvironment for use later in the build process.

var hostBuilder = new HostBuilder()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .ConfigureHostConfiguration(configurationBuilder => {
        configurationBuilder.AddCommandLine(args);
    })
    .ConfigureAppConfiguration((hostingContext, cfg) =>
    {
        // ...

        var env = hostingContext.HostingEnvironment;
        Console.WriteLine(env.EnvironmentName); // Test
        // ...
    });
    
    // ...

    hostBuilder.Build();

In Visual Studio, you configure the application arguments with the same ones as being used by dotnet run which is --environment,
e.g. dotnet run --environment Test.

Without this application argument, the hosting environment defaults back to Production.

enter image description here

like image 118
pfx Avatar answered Oct 09 '22 13:10

pfx


In Visual Studio, you can add an environment variable under the Debug tab of the console application properties. For a console application the environment variable provider name must be prefixed by DOTNET_ for the generic host builder to recognize it. In this case, the provider name is DOTNET_ENVIRONMENT.

Visual Studio 2019 image

If this provider name is not specified, the default is Production.

Reference : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-5.0#host-configuration

like image 34
Gary Chan Avatar answered Oct 09 '22 12:10

Gary Chan


Another method is to use the "UseEnvironnement" method directly on the host builder :

https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.hostinghostbuilderextensions.useenvironment?view=dotnet-plat-ext-5.0

For example :

   public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseEnvironment("dev") // Magic is here
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://0.0.0.0:8081");
                    webBuilder.UseStartup<Startup>();
                });
like image 7
Jérémie Leclercq Avatar answered Oct 09 '22 14:10

Jérémie Leclercq