I need a configuration section something like this:
<myConfig>
<mySubConfig1>
<mySubSubConfig1 keyAttribute="value1">
<mySubSubConfig1Element keyAttribute="value1"/>
<mySubSubConfig1Element keyAttribute="value2"/>
</mySubSubConfig1>
<mySubSubConfig1 keyAttribute="value2">
<mySubSubConfig1Element keyAttribute="value1"/>
</mySubSubConfig1>
</mySubConfig1>
<mySubConfig2>
<mySubSubConfig2 keyAttribute="value1">
<mySubSubConfig2Element keyAttribute="value1"/>
<mySubSubConfig2Element keyAttribute="value2"/>
</mySubSubConfig2>
<mySubSubConfig2 keyAttribute="value2">
<mySubSubConfig2Element keyAttribute="value1"/>
</mySubSubConfig2>
</mySubConfig2>
<mySubConfig3>
<mySubSubConfig3 keyAttribute="value1">
<mySubSubConfig3Element keyAttribute="value1"/>
<mySubSubConfig3Element keyAttribute="value2"/>
</mySubSubConfig3>
<mySubSubConfig3 keyAttribute="value2">
<mySubSubConfig3Element keyAttribute="value1"/>
</mySubSubConfig3>
</mySubConfig3>
</myConfig>
I haven't yet found the magic that would permit this withoug using the old IConfigurationSectionHandler interface. Does anyone know how to do it?
It's ok with me if myConfig and the mySubConfign are ConfigurationSectionGroup or ConfigurationSection.
Also, if it matters, this will be used from web.config.
In your example config file,
myConfigwould be a class that inherits fromConfigurationSectionwith three properties namedmySubConfig1,mySubConfig2andmySubConfig3.The type of the
mySubConfig1property (as well as 2 and 3) would be a class that inherits fromConfigurationElementCollection, implementsIEnumerable<ConfigElement>and is decorated withConfigurationCollection(where the "AddItemName" property is set to "mySubSubConfig1").Below is a complete sample implementation of an approach I used in a production deployment. Be sure to include the System.Configuration assembly. (It's a bit confusing because the System.Configuration namespace is defined in other assmeblies, but you must include the System.Configuration assembly to use the code below.)
Here are the custom configuration classes:
Here's the App.config file:
Finally, here's the code which accesses and uses the config file:
A lighter-weight alternative was written by Sunil Singh on his blog:
http://blogs.quovantis.com/net-creating-a-custom-configuration-section-that-contains-a-collection-of-collections/