I have a custom configuration section registered in the app/web.config, let’s call it MySection. I have an ElementCollection element inside the section, called MyElements. Inside the element collection I want to have elements which are represented by different classes – the idea is that these are similar classes with some common properties and some specific to the instance.
Here is some xml configuration example:
<MySection>
<MyElements>
<Element1 name="someProp1" value="someValue" />
<Element2 name="someProp2" format="{0}{1}" />
</MyElements>
</MySection>
In my simple example, all elements must have a ‘name’ property, some will have also a ‘value’ property, and the other a ‘format’ property.
Here, I want Element1 and Element2 to be represented in the .NET runtime by two different classes which have a common base class that defines the ‘name’ property.
As far as I have dug into .NET configuration, I got the impression that an element collection (like ‘MyElements’ here) should contain homogeneous elements (only of one type). So, could it be possible to achieve what I want – make it contain elements of different classes. The idea is to avoid both having more than one element collection for different element types and not to write all repeating properties for every custom ConfigurationElement implementation.
You can achieve this by overriding OnDeserializeUnrecognizedElement method in your ElementCollection class and creating representations of your Element1 and Element2 by switching on tag name for ex. But AFAIR child elements should be derived from common ancestor anyway, doing it otherwise is too much trouble.
Define collection as:
And child element: