I would like to have an xml config file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="plugins" type="MyApp.PluginsConfiguration, MyApp"/>
</configSections>
<plugins>
<use assembly="MyApp.Plugin1.dll" />
<use assembly="MyApp.Plugin2.dll" />
</plugins>
</configuration>
How exactly do I arrange the interplay between the PluginsConfigurations, UsePluginCollection, and UsePlugin classes in my code?
I found this tutorial online but it would introduce an element inside of plugins that surrounds the use collection and I do not need this.
This is what I have so far but its not quite right
If MyApp.PluginsConfiguration is a ConfigurationSection, then you can define a new Class that inherits from ConfigurationElementCollection and make the new class a ConfigurationProperty of MyApp.PluginsConfiguration
Check this article for some in-depth info about those types. I also blogged about having nested properties, but not specifically for collections.
Edit: Here with some code. Given is this bit in the web.config:
Here is are the classes to make that happen. Note that there maybe NullReferenceExceptions that would need to be handled.
And to access it, this code snippet should help:
Basically we have a ConfigurationSection that handles the plugins-element. In this, we specify a ConfigurationElementCollection property and declare it as the Default Collection (you could in theory have multiple different collections under one root node).
PluginsElementCollection implements the ConfigurationElementCollection. ElementName has to be the name of the tag, in our case “use”. Also, GetElementKey needs to be overridden and should return an attribute that is unique among the entries.
PluginsElement then implements a single use tag. We only define one property: AssemblyName, which is mapped to the assembly-attribute.
I don’t claim to fully understand all of this (Especially ConfigurationElementCollection and it’s various BaseAdd, BaseGet etc. properties are not really explored here), but I can claim that this works 🙂
Also, It doesn’t use any attributes. I hate Attributes – luckily, all these attributes can be converted to proper code. You could use one or the other (or both).