NET Core Configuration Method and Steps for Multi-environment

Time:2019-9-8

Configuration of multi-environment is often used in daily development. After multi-environment configuration, it can avoid the troubles and risks caused by mixing production and testing environments, reduce project risks, and also ensure the security of key in production environment through multi-environment.

When I was doing iOS development, the solution of iOS was to configure different environment variables through multiple Targets, and read different configurations when I started different environments with macros. Of course, there would be a similar way in. NET Core, and it is simpler than in iOS. It only needs to inject different environment variables, that is. However, iOS also needs to set up multiple Targets to inject different environment variables, while. NET Core can inject different environment variables directly at startup without any other operations at all.

Mode 1: Pre-compiled instruction DEBUG

#if DEBUG
      // Read Environment 1 Profile
#else
      // Read Environment 2 Profile
#endif

If you only have two environments, this method is barely enough. In daily development, we basically run in DeBug mode. In production environment, the code released is basically compiled Release code, so use precompiled instructions.#if DEBUGTo meet this requirement, and this operation is very simple, just need to prepare two different configuration files to read to two different environments.

/// <summary>
  /// Global Configuration Management Class (distinguishing environments by DEBUG/RELEASE)
  /// </summary>
  public static class MyConfiguration
  {
    public static IConfiguration Configuration { get; set; }
    static MyConfiguration()
    {
    #if DEBUG
      var envPath = "appsettings.Development.json";
    #else
      var envPath = "appsettings.json";
    #endif
      Configuration = new ConfigurationBuilder()
        .Add(new JsonConfigurationSource
        {
          Path = envPath,
          ReloadOnChange = true
        }).Build();
    }
  }

But if you want to debug the production environment or implement more than two environments, you can only use the second approach.

Mode 2: Injecting different environmental variables

First, prepare configuration files for your different environments, such as:

Then select the launchSettings.json file under the startup project Properties and add the following configuration:


{
 "profiles": {
  "240": {
   "commandName": "240",
   "launchBrowser": true,
   "launchUrl": "",
   "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Dev240"
   }
  },
  "241": {
   "commandName": "241",
   "launchBrowser": true,
   "launchUrl": "",
   "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Dev241"
   }
  },"243": {
   "commandName": "243",
   "launchBrowser": true,
   "launchUrl": "",
   "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Dev243"
   }
  },"Staging": {
   "commandName": "Staging",
   "launchBrowser": true,
   "launchUrl": "",
   "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Staging"
   }
  }
 }
}

At this point, the startup option has become as follows:

Of course, we can also change it directly in the Properties of the startup project, as follows:

Of course, after the environment variables are configured, we need to use the environment variables to create a new configuration tool class file:

/// <summary>
  /// Global Configuration Management Class (Adapting Multiple Environments)
  /// </summary>
  public static class MyConfigurationHelper
  {
    public static IConfiguration Config { get; set; }
    static MyConfigurationHelper()
    {
      var env = BfServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>();
      Config = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)
        .Build();
    }
    
  }

  public static class MyServiceProvider
  {
    public static IServiceProvider ServiceProvider { get; set; }
  }

A read configuration is provided in this file.IConfigurationOfMyConfigurationHelperClass and a ProviderIServiceProviderContainerMyServiceProviderclassIServiceProviderIt’s a service container in. NET Core, which can access the environment variables injected by the program and then enter it.Startup.csRefer to this file, andConfigureIn the method, theIApplicationBuilderOfApplicationServicesPass it in.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
    // Configuring multiple environments
    MyServiceProvider.ServiceProvider = app.ApplicationServices;
  }

At this time, we went back and looked.MyConfigurationHelperClass, which will be used next time, fromIServiceProviderRead the environment variable strings Dev240, Dev241, Dev243, Staging corresponding to the startup environment we selected, so as to read different configuration files andIConfiguration ConfigIn this case, we will use it when we subsequently use the operation of reading configuration files.MyConfigurationHelper.ConfigRead.

Distinguish multiple environments when publishing

On Liunx, we use supervisor to guard our. NET Core application, so we can configure and modify the project configuration of supervisor in which environment we want to run./etc/supervisord.d/The following configuration files are typed into environment variables as follows:

# /etc/supervisord.d/DotNetCoreTest.ini
[program:DotNetCoreTest]
directory=/xxx/DotNetCoreTest
command=dotnet DotNetCoreTest.dll
autostart=true
autorestart=true
user=root
numprocs=1
redirect_stderr=true
stdout_logfile=/xxx/logs/DotNetCoreTest.log
# Environmental variables
environment=ASPNETCORE_ENVIRONMENT=Dev240

The first way is to compile Release to read the configuration file of the corresponding environment automatically without the above operation.

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.

Recommended Today

Write a package for parsing abnormal JSON strings – fbbk-json

F [beep] [beep] K JSON Parse a package of abnormal JSON strings. install $ npm install fbbk-json Use This package has only one function: var fJSON = require(“fbbk-json”); fJSON.parse(A_JSON_STRING); however This package supports the following JSON strings (that is, what we usually declare in javascript, without quotation marks). Raise a chestnut. ‘{foo”:”bar”,”baz”: true} < – […]