gpt4 book ai didi

docker - 在 .NET Core 中将应用设置与环境变量合并

转载 作者:IT老高 更新时间:2023-10-28 21:34:09 26 4
gpt4 key购买 nike

我正在 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)两个单独的配置,然后在代码中“手动”合并它们,但这种解决方案是不可取的。

最佳答案

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

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

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

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

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

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

另请注意:来自 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com