Loading config values from app settings and environment

1k views Asked by At

Think I'm having a brain melting moment but is it possible to load configuration from both appsettings and environment variables? I have some config that looks like

    "DataFactorySettings": {
        "ClientId": "foobar",
        "FactoryName": "factory",
        "PipelineName": "pipeline",
        "PipelineParameters": "params",
        "ResourceGroup": "rg",
        "Subscription": "sub",
        "TenantId": "tenant"
    }

I have an environment variable entitled DATAFACTORYSETTINGS_CLIENTSECRET which contains the value secret.

My configuration class that binds to this looks like:

public class DataFactorySettings
{
    public string ClientId { get; set; }

    public string ClientSecret { get; set; }

    public string FactoryName { get; set; }

    public IDictionary<string, string> ParsedPipelineParameters { get; }

    public string PipelineName { get; set; }

    public string PipelineParameters { get; set; }

    public string ResourceGroup { get; set; }

    public string Subscription { get; set; }

    public string TenantId { get; set; }
}

Got a basic console app that has the following setup

var config = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .AddJsonFile("appsettings.json", optional:false)
    .Build();

For me to bind all these values together I do the following:

var a = new DataFactorySettings();
config.Bind("DataFactorySettings", a); // binds only appsettings.json
a.ClientSecret = config["DATAFACTORYSETTINGS_CLIENTSECRET"]; // grab env variable

I have two questions:

  1. Is there a way to do this out the box so it will automatically bind?
  2. If I had all the configuration as environment variables can I bind this to a concrete type in one go like I can do with appsettings?
1

There are 1 answers

0
SBFrancies On BEST ANSWER

Not 100% sure on this but I think a single underscore doesn't indicate a nested property. Either of the following may work depending on your OS:

DATAFACTORYSETTINGS__CLIENTSECRET (note the double underscore)

DATAFACTORYSETTINGS:CLIENTSECRET

The Bind should then work as you expect.