Setting environment variables for dotnetcore Windows service -- process only, not system or user

Viewed 4104

Our developers are writing some Windows Services in .NET Core 3.1.

As I understand it, the typical pattern for Core development is to check the DOTNET_ENVIRONMENT variable to switch on different configurations.

For ReasonsTM, we want to avoid setting system-level or even user-level machine environment variables. Some of the reasons are:

  • something else to set up when rolling out a new server
  • might want to run different "environments" on the same server -- not for services, maybe, but for other commandline apps

For Kestrel hosted apps launched by IIS, extra environment values can be set in web.config. This can't apply to commandline apps.

What's the best practice for this? Is there a way to set environment variables before launching the executable? Or set environment variables within the process, at startup time, by reading them from a config file?

Other things to mention:

2 Answers

Buried in the documentation under Environment variable configuration provider is the following extract:

The default configuration loads environment variables and command-line arguments prefixed with DOTNET_. The DOTNET_ prefix is used by .NET for host and app configuration, but not for user configuration.

So if you use the command line parameter --environment Development that should get transformed into DOTNET_ENVIRONMENT=Development. This was tested as working with a .NET 5.0 worker service.

I've settled on this answer: To all appearances, a .NET core app starting up will not, by default, look at any config files to set environment variables. So, either the code has to set its own environment variables by adding code to do so, or a wrapper app is necessary to set those variables before spawning the app.

Related