Mar*_*cus 8 config environment-variables 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; }
}
Run Code Online (Sandbox Code Playgroud)
我设置了appsettings
这样的:
config.
AddJsonFile("appsettings.json").
AddJsonFile($"appsettings.docker.json", true).
AddEnvironmentVariables();
Run Code Online (Sandbox Code Playgroud)
DI设置:
services.Configure<EnvironmentConfiguration>(Configuration);
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我使用它:
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
我跑码头:
docker run -p 4000:5000 --env-file=myvariables
Run Code Online (Sandbox Code Playgroud)
该文件myvariables
如下所示:
EXAMPLE_SETTING=example!!!
MY_SETTING_2=my-setting-2!!!!
Run Code Online (Sandbox Code Playgroud)
这有效.我可以使用我的_environmentConfiguration
并看到我的变量已设置.
但是...我想将环境变量与appsettings合并,以便在找不到环境变量时将appsettings的值用作回退.以某种方式合并这两行:
services.Configure<EnvironmentConfiguration>(settings => Configuration.GetSection("EnvironmentConfiguration").Bind(settings));
services.Configure<EnvironmentConfiguration>(Configuration);
Run Code Online (Sandbox Code Playgroud)
这有点可能吗?
我的后备计划是继承EnvironmentConfiguration
该类并使用单独的DI来注入两个单独的配置,然后在代码中"手动"合并它们,但这种解决方案是不可取的.
Has*_*san 20
config.
AddJsonFile("appsettings.json").
AddJsonFile("appsettings.docker.json", true).
AddEnvironmentVariables();
Run Code Online (Sandbox Code Playgroud)
实际上足以使用环境变量覆盖appsettings值.
假设您在appsettings.json文件中有以下内容;
{
"Logging": {
"Level": "Debug"
}
}
Run Code Online (Sandbox Code Playgroud)
您可以Logging.Level
通过将环境可变"Logging:Level"设置为另一个值来覆盖值.
请注意,:
它用于指定环境变量键中的嵌套属性.
来自docs ;
如果冒号(:)不能在系统上的环境变量中使用,请将冒号(:)替换为双下划线(__).
归档时间: |
|
查看次数: |
7791 次 |
最近记录: |