Search code examples
c#dependency-injectionconfigurationsection

Unable to set nested json value via ConfigurationSettings


I have a class in Package XYZ say:

public class Temp
{
    string a;
    string b;
    string c; 
 }

Another class in same package:

public class Other
{
    public int id {get; set;}
    public Temp temp {get;set;}
}

Now the values for Temp and id variables for class Other come from appsettings.json of another project which looks like:

...some settings
"Other":{
  "id":2
 "Temp":{
  "a":"Hey",
  "b":"Hello",
  "c":"Bye"
 }
},
...rest of the settings

Now, in the package extension class, I am trying to set the values as:

id = configuration.GetValue<int>("Other:id"); // 2 here
Temp = configuration.GetValue<Temp>("Other:Temp");  //null here

Not sure why this value isn't get set.

I tried: Temp = configuration.GetSection("Other:Temp") but that can't convert it to instance of type Temp.

Is there any way to achieve this? Thanks in advance.


Solution

  • Fixed this by adding :

    Temp = new Temp
    {
       a = configuration.Get<string>("Other:Temp:a"),
       b = configuration.Get<string>("Other:Temp:b"),
       c = configuration.Get<string>("Other:Temp:c")
    }