Reputation: 603
I have a base class which I'm using JsonDerivedType
to do serialization / deserialization of derived types. Works nicely.
However, rather than having to add the JsonDerivedType
attribute explicitly whenever a new derived type is added to the app and rebuilt, as follows:
[JsonDerivedType(typeof(MyConfigDerived), typeDiscriminator: "derived")]
[JsonDerivedType(typeof(MyConfigAlternate), typeDiscriminator: "alternate")]
[JsonDerivedType(typeof(MyConfigAnother), typeDiscriminator: "another")]
I'd really like to discover all derived types and add them automatically at runtime, based on a convention.
So if I have a base class like this:
[JsonDerivedType(typeof(MyConfigBase), typeDiscriminator: "base")]
public class MyConfigBase { ... }
I'd like to just be able to declare:
public class MyConfigDerived : MyConfigBase { ... }
public class MyConfigAlternate : MyConfigBase { ... }
public class MyConfigAnother : MyConfigBase { ... }
and have them auto-discovered through the type system at startup so they all work. The reason I'd like to avoid using attributes is because I want collaborators to be able to register new types and have them serialize/deserialize correctly, without needing to alter the attributes on the base class, to make it easier for people to add new implementations.
I found this SO article, which seems to sort of go half-way, but does anyone have an example of an auto-registering-all-derived-classes code that would do what I need?
Upvotes: 0
Views: 46