Bind an IConfigurationSection to a complex object without ASP.NET Core

Maximilian Ast picture Maximilian Ast · Jul 11, 2017 · Viewed 22.7k times · Source

I have a .NET Core console application and want to read the appsettings.json and parse a section as List<Param> (without Dependency Injection or ASP.NET Core).
I already tried How do I bind a multi level configuration object using IConfiguration in a .net Core application? but it seems like .Get<T>() got removed from netcoreapp1.1

IConfigurationSection myListConfigSection = configurationRoot.GetSection("ListA");

List<Param> paramList;

//Get does not exist
//paramList = myListConfigSection.Get<Param>();

string paramListJson = myListConfigSection.Value // is null
// won't work neither because paramListJson is null
paramList = JsonConvert.DeserializeObject<Param>(paramListJson);

appsettings.json:

{
  "ListA": [
    { "ID": "123", "Param": "ABC"},
    { "ID": "123", "Param": "JKS"},
    { "ID": "456", "Param": "DEF"}
  ]
}

Is there an easy way to load the config into the object or do I have to read the config file again and parse it myself with JsonConvert?

Answer

Treziac picture Treziac · Jul 11, 2017

Get<T> is defined in package Microsoft.Extensions.Configuration.Binder