Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind a multi level configuration object using IConfiguration in a .net Core application?

I'm trying to bind to a custom configuration object which should be populated by an appsettings.json file.

My appsettings looks a bit like:

{
  "Logging": {
    "IncludeScopes": true,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Settings": {
    "Foo": {
      "Interval": 30,
      "Count": 10
    }
  }
}

The settings classes look like:

public class Settings
{
  public Foo myFoo {get;set;}
}

public class Foo
{
  public int Interval {get;set;}
  public int Count {get;set;}

  public Foo()
  {}

  // This is used for unit testing. Should be irrelevant to this question, but included here for completeness' sake.
  public Foo(int interval, int count)
  {
    this.Interval = interval;
    this.Count = count;
  }
}

When I try to bind the Configuration to an object the lowest level it works:

Foo myFoo = Configuration.GetSection("Settings:Foo").Get<Foo>();

myFoo correctly has an Interval and a Count with values set to 30 and 10 respectively.

But this doesn't:

Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();

mySettings has a null foo.

Frustratingly, if I use the debugger I can see that the necessary data is being read in from the appsettings.json file. I can step down into Configuration => Non-Public Members => _providers => [0] => Data and see all of the information I need. It just won't bind for a complex object.

like image 487
Necoras Avatar asked Dec 28 '16 21:12

Necoras


People also ask

Can I add more than two Appsettings json files in dotnet core?

Can I add more than two appsettings. json files in dotnet core? Of course, we can add and use multiple appsettings. json files in ASP.NET Core project.

What is IConfiguration C#?

The IConfiguration is an interface for . Net Core 2.0. The IConfiguration interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IConfiguration interface is used to read Settings and Connection Strings from AppSettings. json file.


2 Answers

Your property must match the property names in "appsettings.json".

You must rename your Settings' myFoo property into Foo, because that's property name in the json file.

like image 150
Tseng Avatar answered Oct 24 '22 03:10

Tseng


You can also use the JsonProperty(Included in Newtonsoft.Json) Annotation to tell the serializer what to do like below.

public class Settings
{
  [JsonProperty("Foo")]
  public Foo myFoo {get;set;}
}
like image 1
Patrick Mcvay Avatar answered Oct 24 '22 02:10

Patrick Mcvay