Visual Studio Net Core: Switch Environment Variables for Multiple Projects

Viewed 2316

We have multiple Projects in a Solution, and need a way to quickly change Environment to Another One, say QA. There are 8 projects in our solution. How can this be done, without manually going through each ?

Is there quick setting in Visual Studio?

enter image description here

Note: We have a multiple number of API projects, which have non dependencies.

4 Answers

One way to solve this is to have a solution-level "environment" text file, that each API project can "link" to. Then in each API project's Program or Startup logic, have them read this global file to set the environment at run time.

As an example, here's my sample solution which has 2 API projects in it:

enter image description here

Step 1: Create The 'Global' Environment File

Firstly, I added a solution-level text file Environment.txt that simply has the name of the 'current' environment I wish to run all my API's under:

Performance

Step 2: Link The Environment.txt File To Each API Project

Second is linking the Environment.txt file to each API project, using Visual Studio's Add Existing Item dialog, and choosing the Add As Link option:

enter image description here

Notice that the icon on linked files is slightly different than a normal file.

Step 3: Ensure Environment.txt Actually Gets Copied To The Bin Directory(s)

Thirdly is ensuring that each of the added linked file's Copy to Output option is set to Copy Always:

enter image description here

Step 4: A Small Bit Of Code...

And finally, in each API project's Program.cs file, you can read this file and set the environment at run-time:

namespace MicroserviceSandbox.ApiTwo
{
    using System.IO;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Hosting;

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    // *** Dynamically set the environment.
                    var binDirectoryPath = new FileInfo(typeof(Program).Assembly.Location).Directory.FullName;
                    var environmentFilePath = Path.Combine(binDirectoryPath, "Environment.txt");
                    var environment = File.ReadAllText(environmentFilePath);
                    webBuilder.UseEnvironment(environment);
                    // ***

                    webBuilder.UseStartup<Startup>();
                });
        }
    }
}

Assumptions

  • The above C# code snippet assumes your API projects are using ASP.NET Core v3.1.

As shown on your screenshot, the "app environment" is determined by that "windows process environment variable". Only the project that is being run needs to set that environment variable, not the projects refenced by that one.

If you are running multiple projects at the same time: The environment variable is saved to the launchSettings.json file in the project folder. You could us a PowerShell script to update the launchSettings of many projects at once.

Instead of using the environment variables from the project launchsettings, you can also use the system environment variables.

To do so, you have to remove the "ASPNETCORE_ENVIRONMENT" from the launchsettings and set in system enviroment variables. See docu here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-3.1#set-the-environment

Caution: Every project on the same machinge not having the "ASPNETCORE_ENVIRONMENT" set in the launchsetting will use the system enviroment variable

There a couple of things described in the articles below:

  1. Automatically set appsettings.json for dev and release environments

  2. launchSettings.json in ASP.NET

  3. Various configuration json files in ASP.NET

The first one is a step by step instruction how to set up appsettings.json for multiple environments; in the 2nd article you find important information about launchSettings.json and how different sets of environment variables can be configured. Here you'll find an example how you can set up environment variables for 3 different configurations like "Development", "Staging" and "Production".

Also there are startup conventions in Startup.cs like "StartupDevelopment" or "StartupProduction" being called if you switched the deployment platform.

Essentially, to set this up, you'll need a combination of these to set up your environment variables properly. I'd use ajawad987's answer but change the environment file path to var environmentFilePath = Path.Combine(binDirectoryPath,$"Environment.{env.EnvironmentName}.txt");, allowing to set it depending to the environment (the variable comes from Startup(IHostingEnvironment env) - you might need to add a global property accessible from his code). His code should be added to all projects. Note that you can either set up ASPNETCORE_ENVIRONMENT as system environment variable or run it via commandline like dotnet run --environment "Development".

But note you can also declare environment variables in the launchSetting.json file, e.g.

"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "environmentVariables": {
    "Hosting:Environment": "Development"
  }
},

This JSON file holds project specific settings associated with each profile Visual Studio is configured to use to launch the application.

What is also worthwhile is to look into is the 3rd article about Various configuration json files in ASP.NET, there you can find a description of all json files that exist in current ASP.NET Core projects, and what role they are playing in your project.

It is a pitty that the inventors of .NET core didn't implement that more straightforward!

Related