Search code examples
c#.netapp-configsystem.configurationcustom-configuration

ConfigurationElementCollection with a number of ConfigurationElements of different type


Is it possible to have a CollectionElementCollection with a number of different by type CollectionElements, e.g.:

<collection>
    <add type="MyType1, MyLib" Type1SpecificProp="1" />
    <add type="MyType2, MyLib" Type2SpecificProp="2" />
</collection

I have all classes required for such solution:

class MyCollection : ConfigurationElementCollection { }
class MyElement : ConfigurationElement { }
class MyType1 : MyElement { }
class MyType2 : MyElement { }
...
etc

but when I start my application I'm getting next predictable error:

Unrecognized attribute 'Type1SpecificProp'.

because Type1SpecificProp is defined in MyType1 not MyElement, especially if MyCollection has next method:

protected override ConfigurationElement CreateNewElement()
{
    return new MyElement(); // but I want instantiate not the base class but by a type given
}

i.e. returns base class thus OnDeserializeUnrecognizedAttribute() in child classed are never been called.

So the question is: how to let child classes to resolve unknown elements by their self?


Solution

  • Microsoft.Practices.EnterpriseLibrary.Common.Configuration.PolymorphicConfigurationElementCollection<T> from EntLib5 do this job as a charm.