Merging appsettings with environment variables in .NET Core

岁酱吖の 提交于 2020-06-24 08:22:42

问题


I am running a .NET Core app in Docker (in Kubernetes), passing environment variables to the Docker container and using them in my app.

In my .NET Core app I have the following C# class:

public class EnvironmentConfiguration
{
    public string EXAMPLE_SETTING { get; set; }
    public string MY_SETTING_2 { get; set; }
}

And I setup my appsettings as such:

config.
    AddJsonFile("appsettings.json").
    AddJsonFile($"appsettings.docker.json", true).
    AddEnvironmentVariables();  

DI setup:

services.Configure<EnvironmentConfiguration>(Configuration);

And in my Controller I use it as such:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/my")]
public class MyController : Controller
{
    private readonly IOptions<EnvironmentConfiguration> _environmentConfiguration;

    public MyController(IOptions<EnvironmentConfiguration> environmentConfiguration)
    {
        _environmentConfiguration = environmentConfiguration;
    }
}       

I run docker:

docker run -p 4000:5000 --env-file=myvariables

The file myvariables looks like this:

EXAMPLE_SETTING=example!!!
MY_SETTING_2=my-setting-2!!!!

This works. I can use my _environmentConfiguration and see that my variables are set.

However... I would like to merge environment variables with appsettings so that the values from appsettings are used as fallback when environment variables are not found. Somehow merging these two lines:

services.Configure<EnvironmentConfiguration>(settings => Configuration.GetSection("EnvironmentConfiguration").Bind(settings));
services.Configure<EnvironmentConfiguration>(Configuration);

Is this somehow possible?

My fallback plan is to inherit from the EnvironmentConfiguration class and use a separate DI to have two separate configurations injected and then merge them "manually" in code but this solution is undesirable.


回答1:


config.
    AddJsonFile("appsettings.json").
    AddJsonFile("appsettings.docker.json", true).
    AddEnvironmentVariables();

is actually enough to override appsettings values using environment variables.

Let's say you have the following in your appsettings.json file;

{
  "Logging": {
      "Level": "Debug"
  }
}

you can override value of Logging.Level by setting the environment variable named Logging:Level to the value of your preference.

Be aware that : is used to specify nested properties in environment variable keys.

Also note: from docs;

If a colon (:) can't be used in environment variable names on your system, replace the colon (:) with a double-underscore (__).



来源:https://stackoverflow.com/questions/48298284/merging-appsettings-with-environment-variables-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!