简体   繁体   中英

.NET 6 C# configuration section variation

I am building a console app using .NET 6. To load the settings I am using the Options Pattern and I want to create json config file with a collection of objects that has variations in one of its properties.

Example json:

{
  "Persons": [
    {
      "Name": "Josh Wink",
      "Information": {
        "SSN": "BC00020032",
        "VatId": "100099332"
      },
      "Characteristics": {
        "Gender": "male",
        "Age": 23
      }
    },
    {
      "Name": "Peter Gabriel",
      "Information": {
        "SSN": "GH00092921",
        "VatId": "100003322"
      },
      "Characteristics": {
        "EyeColor": "brown",
        "HairColor": "black"
      }
    }
  ],
  "SomeOtherSection": "Some Value"
}

I thought of using an empty interface for the Characteristics property, but I don't know how to map this section using Configuration.GetSection().Bind() or Configuration.GetSection().Get

Here are the classes I created

class PersonsCollection
{
    List<Person> Persons { get; set;} = new();
}
class Person
{
    string Name { get; set; } = String.Empty;
    PersonInfo Information { get; set; } = new();
    ICaracteristics? Characteristics { get; set; }
}
class PersonInfo
{
    string SSN { get; set; } = String.Empty;
    string VatId { get; set; } = String.Empty;
}
interface ICaracteristics
{

}
class PersonCharacteristicsType1 : ICaracteristics
{
    string Name { get; set; } = String.Empty;
    int Age { get; set; } = 0;
}
class PersonCharacteristicsType2 : ICaracteristics
{
    string EyeColor { get; set; } = String.Empty;
    string HairColor { get; set; } = String.Empty;
}

There are multiple problems with your classes. First of all you are missing public access modifiers for properties.

Secondary binder can't bind your ICaracteristics? Characteristics ICaracteristics? Characteristics property cause it is an interface and binder does not know how to convert data to it. You can introduce concrete class here which will have all the possible properties:

class PersonsCollection
{
    public List<Person> Persons { get; set;} = new();
}
class Person
{
    public string Name { get; set; } = String.Empty;
    public PersonInfo Information { get; set; } = new();
    public Characteristics? Characteristics { get; set; }
}
class Characteristics
{
    public string Name { get; set; } = String.Empty;
    public int Age { get; set; } = 0;
    public string EyeColor { get; set; } = String.Empty;
    public string HairColor { get; set; } = String.Empty;
}

class PersonInfo
{
    public string SSN { get; set; } = String.Empty;
    public string VatId { get; set; } = String.Empty;
}

And then handle the "types" in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM