OGeek|极客世界-中国程序员成长平台

标题: docker - 在 .NET Core 中将应用设置与环境变量合并 [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-3 10:13
标题: docker - 在 .NET Core 中将应用设置与环境变量合并

我正在 Docker 中(在 Kubernetes 中)运行一个 .NET Core 应用程序,将环境变量传递给 Docker 容器并在我的应用程序中使用它们。

在我的 .NET Core 应用程序中,我有以下 C# 类:

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

然后我设置了我的 appsettings像这样:

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

DI设置:

services.Configure<EnvironmentConfiguration>(Configuration);

在我的 Controller 中,我这样使用它:

[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;
    }
}       

我运行 docker :
docker run -p 4000:5000 --env-file=myvariables

文件myvariables看起来像这样:
EXAMPLE_SETTING=example!!!
MY_SETTING_2=my-setting-2!!!!

这有效。我可以用我的 _environmentConfiguration并看到我的变量已设置。

但是...我想将环境变量与 appsettings 合并,以便在找不到环境变量时将 appsettings 中的值用作后备。以某种方式合并这两行:

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

这有可能吗?

我的后备计划是从 EnvironmentConfiguration 继承类并使用单独的 DI 注入(inject)两个单独的配置,然后在代码中“手动”合并它们,但这种解决方案是不可取的。



Best Answer-推荐答案


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

实际上足以使用环境变量覆盖 appsettings 值。

假设您的 appsettings.json 文件中有以下内容;

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

您可以覆盖 Logging.Level 的值通过设置名为 Loggingevel 的环境变量到您的偏好值。

请注意 :用于在环境变量键中指定嵌套属性。

另请注意:来自 docs ;

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

关于docker - 在 .NET Core 中将应用设置与环境变量合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48298284/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) Powered by Discuz! X3.4