ASP.NET Core Configuration Section in Startup

asked9 years ago
last updated9 years ago
viewed39.3k times
Up Vote51Down Vote

I am migrating a ASP.NET 5 RC1 project to ASP.NET Core, and have come across an interesting issue I've not yet seen, or found a solution for.

In order to use configuration settings within Startup I have previously retrived the configuration the following way

// Works fine for DI both in ASP.NET 5 RC1 and ASP.NET Core
services.Configure<SomeConfigurationClass>(Configuration.GetSection("SomeConfigurationSection"));

// How I previous retrieved the configuration for use in startup. 
// No longer available in ASP.NET Core
var someConfigurationToUseLater = Configuration.Get<SomeConfigurationClass>("SomeConfigurationSection");

After updating to ASP.NET Core 1.0 it seems Configuration.Get() is no longer available.

I have tried updating the code to use Configuration.GetValue() however this does not seem to work with objects and will only work when providing a path to a value. This has left me with a workaround for of my configuration classes like so

var someConfigurationName = "someConfiguration";    
var someConfigurationClass = new SomeConfigurationClass()
{
    Value1 = Configuration.GetValue<string>($"{someConfigurationName}:value1"),
    Foo = Configuration.GetValue<string>($"{someConfigurationName}:foo"),
    Bar = Configuration.GetValue<string>($"{someConfigurationName}:bar")
};

However this is an issue when the configuration class contains an array of objects. In my case an array of Client objects

public class ClientConfiguration
{
    public Client[] Clients { get; set; }
}

With the following configuration

"configuredClients": {
  "clients": [
    {
      "clientName": "Client1",
      "clientId": "Client1"
    },
    {
      "clientName": "Client2",
      "clientId": "Client2"
    }
  ]
}

Where this would previously bind to the Clients property of my configuration class no problem, I can no longer find a way of doing so in ASP.NET Core 1.0