C# strongly typed ConfigurationBuilder List<object> from appsettings
Asked Answered
I

1

6

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.

Isomeric answered 10/6, 2020 at 11:47 Comment(2)
var config = new AppSettings(); Configuration.GetSection("AppSettings").Bind(config); It should work alike for just the names section if you prefer thatSuellen
Yeh have tried this as there was a lot about binding online, this is what I get: "Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<Names.Names>"Isomeric
L
15

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

Linehan answered 10/6, 2020 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.