Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspNet Core 2.0 Windows Service and unique ASPNETCORE_ENVIRONMENT variable

I have an ASPNET Core 2.0 Windows Service executing on server A. It was created using:

sc create...

Server A has sytem ASPNETCORE_ENVIRONMENT="Staging". The Windows Service uses appsettings.Staging.json for settings.

I want to install a duplicate Windows service for demo purposes, which needs to point to appsettings.demo.json for settings.

How can the ASPNET Core 2.0 demo Windows Service execute with an unique ASPNETCORE_ENVIRONMENT="Demo"?

Thanks.

like image 621
paultechguy Avatar asked Jun 20 '18 22:06

paultechguy


1 Answers

I had this exact issue and you can actually set the environment through passing in a command line argument. You will need to create your service like so:

sc create MyDemoService binPath= "C:\MyDemoService.exe --environment Demo"

That will pass in an argument that you can then use in your Main function in Program.cs when building your WebHost. Like so:

var builder = new ConfigurationBuilder();
builder.AddCommandLine(args);
var config = builder.Build();

var host = new WebHostBuilder()
    .UseConfiguration(config)
    ...

As I'm accessing the appsettings.{EnvName}.json elsewhere in my application I have needed to register the IHostingEnvironment as singleton and then I can read the environment name for that service only without having to set the ASPNETCORE_ENVIRONMENT.

like image 71
MattjeS Avatar answered Oct 15 '22 08:10

MattjeS