views:

31

answers:

1

Is there a way to make a configuration section that would allow a freeform XML body? How would I get that freeform body in code?

For example I'd like to create a ModuleConfigurationSection like this:

<modules>
    <module name="ModuleA" type="My.Namespace.ModuleA, My.Assembly">
        <moduleConfig>
            <serviceAddress>http://myserver/myservice.svc&lt;/serviceAddress&gt;
        </moduleConfig>
    </module>
    <module name="ModuleB" type="My.Namespace.ModuleB, My.OtherAssembly">
        <moduleConfig>
            <filePath>c:\directory</filePath>
        </moduleConfig>
    </module>
</modules>

So some code would spin up each of these module types from config sections using ConfigurationManager.GetSection("modules") and I'd like to pass the XML inside the moduleConfig element as an opaque configuration value to the constructor of the module class.

Any input appreciated!

A: 

This is how I ended up accomplishing this:

public class ModuleElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get { return (string)base["name"]; }
        set { base["name"] = value; }
    }

    XElement _config;
    public XElement Config
    {
        get { return _config;  }
    }

    protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader)
    {
        if (elementName == "config")
        {
            _config = (XElement)XElement.ReadFrom(reader);
            return true;
        }
        else
            return base.OnDeserializeUnrecognizedElement(elementName, reader);
    }
}

So the xml would look like:

<module name="ModuleA">
    <config>
        <filePath>C:\files\file.foo</filePath>
    </config>
</module>

The body of the config element could be any freeform xml that you like. Assuming that you set up a collection, when you do ConfigurationManager.GetSection("modules") you can then access the Config property of each ModuleElement object as an XElement representing the XML of the config element node.

joshperry