Rob
Rob

Reputation: 7237

How to map config in IConfigurationSection to a simple class

Using MVC .net Core and building a concrete config class within the startup class. My appsettings.json looks like this:

{
    "myconfig": {
        "other2": "tester",
        "other": "tester",
        "root": {
            "inner": {
                "someprop": "TEST VALUE"
            }
        }
    }
}

I've represented this with a concrete class as follows:

public class TestConfig
{
    public string other2 { get; set; }
    public string other { get; set; }
    public Inner1 root { get; set; }
}

public class Inner1
{
    public Inner2 inner { get; set; }
}

public class Inner2
{
    public string someprop { get; set; }
}

And I can easily map this by doing the follow:

var testConfig = config.GetSection("myconfig").Get<TestConfig>();

However.... what I don't like about the above is the need to make TestConfig more complex than it needs to be. Ideally, I'd like something like this:

public class PreciseConfig
{
    [Attribute("root:inner:someprop")]
    public string someprop { get; set; }
    public string other { get; set; }
    public string other2 { get; set; }
}

Where I don't have to have the nested objects within and can map directly to a lower property in this kind of way. Is this possible? Using .net Core 2.1.

Thanks for any pointers in advance!

P.s. I know I can create an instance of PreciseConfig myself and set properties using config.GetValue<string>("root:inner:someprop") BUT I don't want to have to set all my custom settings in this way if I can do them automatically using a serialization property or similar.

Upvotes: 25

Views: 37663

Answers (1)

Nkosi
Nkosi

Reputation: 247413

For the higher level config you get the configuration as normal with the top node.

Then use the path myconfig:root:inner to get the other desired section and Bind PreciseConfig from the previous step

var preciseConfig = config.GetSection("myconfig").Get<PreciseConfig>();

config.GetSection("myconfig:root:inner").Bind(preciseConfig);

Reference Configuration in ASP.NET Core : GetSection

Reference Configuration in ASP.NET Core : Bind to an object graph

Upvotes: 34

Related Questions