Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Environment Variables to Class Using IConfigurationRoot

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?

like image 516
Son_of_Sam Avatar asked Feb 05 '23 05:02

Son_of_Sam


1 Answers

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}");
like image 82
Triplesticks Avatar answered Feb 08 '23 16:02

Triplesticks