1

I'm trying to get the parameter from my appsettings.json which is a list of derived classes. The problem is that I don't know how I can retrieve the information and create the object with the good class for each item get.

My appsettings.json is something like this :

"DiagnosticSettings": {
"Diagnostics": [
  {
    "Type": "Connection",
    "Address": "xxx"
  },
  {
    "Type": "DNS",
    "DNSAddress": "www.google.com",
    "IPToCompare": "8.8.8.8"
  },
  {
    "Type": "DNS",
    "DNSAddress": "www.abc.com",
    "IPToCompare": "x.x.x.x"
  }, [...] 
]}

I have a base class :

public class BaseDiagnosticConfig
{
    public string Type { get; set; }
}

And derived classes like :

public class DNSDiagConfig : BaseDiagnosticConfig
{
    public string DNSAddress { get; set; }
    public string IPToCompare { get; set; }
}

I can retrieve the provider which contains the list of items with something like this :

var a = Configuration.GetSection("DiagnosticSettings:Diagnostics");

And I can have the list of base class (but it is not what I want as I lost all the derived classes information) :

var b = Configuration.GetSection("DiagnosticSettings:Diagnostics").Get<List<BaseDiagnosticConfig>>();

So there is a way to get my items which the good class even if I had to check one by one all the items in my appsettings list or I am just doing something impossible/wrong ?

1
  • You are paddling against the stream here, what not use a list of class with a property called Type, and a dictionary of attributes? or even make it all just a dictionary with dictionary of attributes Commented Jun 26, 2020 at 6:20

1 Answer 1

0

You have to do like this. I am providing you a very simple example, you can use according to your requirement.

"MySettings": {  
    "Email": "[email protected]",   
  }


public class MySettingsModel  
{   
       public string Email { get; set; }  
}

Register it

services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));

Declare in the class in which you want to read the setting.

private readonly IOptions<MySettingsModel> appSettings; 
public StudentController(IOptions<MySettingsModel> app)  
{  
    appSettings = app;  
}

Read the value

var value = appsettings.Value;

Reference: https://www.c-sharpcorner.com/article/reading-values-from-appsettings-json-in-asp-net-core/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.