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.