In dotnet core I want to bind a set of environment variables to a class using IConfigurationRoot
and the Bind
method similar what you do with the appsettings.json
For Example
having the following appsettings.json
{
"EnviromentSettings":
{
"ValueOne": "Foo1",
"ValueTwo": "Foo2"
}
}
I can bind the section EnvimentSettings
to the following class
public class EnviromentSettings
{
public string ValueOne {get;set;}
public string ValueTwo {get;set;}
}
using this code
public IConfigurationRoot Configuration { get; }
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
services.Configure<EnviromentSettings>(options => Configuration.GetSection("EnviromentSettings").Bind(options));
Can I do something similar for environment variables?
Yes, just remove "EnvironmentSettings" from the appsettings.json file. This works for me. Note: It will read from the appsettings.json file first and over-ride with environment variables, if they exist.
appsettings.json
{
"ValueOne": "Foo1",
"ValueTwo": "Foo2"
}
code changes
EnvironmentSettings settings = new EnvironmentSettings();
var builder = new ConfigurationBuilder()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
config = builder.Build();
ConfigurationBinder.Bind(config, settings);
Console.WriteLine($"ValueOne: {settings.ValueOne}");
Console.WriteLine($"ValueTwo: {settings.ValueTwo}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With