mercredi 30 octobre 2019

Read configuration in to a collection of base class objects as child class objects

I have .Net core application, which is using the appsettigs.json file for holding configuration. I need to load a configuration section into a collection, without iterating through them. I know I can use Bind() method to bind the collection into a collection of same type. But here I am trying to get objects of the child class type in the collection, instead of base class type.

"Sections": [
{
  "Name": "Section 1",
  "Type":"type1"

},
{
  "Name": "Section 2",
  "Type":"type2"

},
{
  "Name": "Section 3",
  "Type":"type1"

},
{
  "Name": "Section 4",
  "Type":"type1"

},
{
  "Name": "Section 5",
  "Type":"type2"

}]

I am using the below code to read the config file.

var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        var Configuration = configBuilder.Build();

I know I can use Configuration.Bind()

The classes are

    Public abstract class BaseSection:ISection
    {
    public string Name;
    ..
    }


Public class Type1:BaseSection
{
public string Name;
..
}

Public class Type2:BaseSection
{
public string Name;
..
}

I need to read the configuration from the appsettings.json file to List such that the the for entry in config file with "type=type1" will have type in the collection Type1 obejct and "type=type2" will have type in the collection Type2 obejct.

So my collection from the above config entries should have

[
    Object Of Type1
    Object Of Type2
    Object Of Type1
    Object Of Type1
    Object Of Type2
]

I don't want to read the data once and then type cast it.

Please share views and inputs. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire