C# strongly typed ConfigurationBuilder List<object> from appsettings

3.3k Views Asked by At

Really struggling with this one - is it supposed to be this hard?!

I have a simple object array in my appsettings:

"AppSettings": {
    "Names": [
      {
        "Id": "1",
        "Name": "Mike"
      },
      {
        "Id": "2",
        "Name": "John"
      }    
    ]
}

I then have a class

public class AppSettings
{
    public List<Names> Names { get; set; } = new List<Names>();
}

public class Names
{
    public string Id { get; set; }
    public string Name { get; set; }
}

I read in my app settings:

var configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appSettings.json").Build();

var config = new AppSettings();

This is where stuff goes wrong:

config.Names = configuration.GetSection("AppSettings:Names") //<<<< what do I do here?

It seems like it's all tied to IConfigurationSection which is not helpful.

1

There are 1 best solutions below

0
On BEST ANSWER

Get the entire object graph from the setting using the ConfigurationBinder.Get<T> extension.

ConfigurationBinder.Get<T> binds and returns the specified type. ConfigurationBinder.Get<T> may be more convenient than using ConfigurationBinder.Bind. The following code shows how to use ConfigurationBinder.Get<T> with the AppSettings class:

//...

AppSettings config = configuration.GetSection("AppSettings").Get<AppSettings>();

//...

Reference Configuration in ASP.NET Core