Reading EntLib 4.1 configuration from an in-memory XML string

437 views Asked by At

I'd like to use the EntLib 4.1 in my current project, specifically Unity 1.2 and the VAB. My application is an SaaS application, so I've made a decision to store tenant-specific configuration files in the database, to be loaded on tenant sign-in. These files include the VAB config and Unity config, as well as other tenant-specific settings.

I can't find any practical way to simply use an XML string as my configuration info for the VAB.

I first thought that I'd have to create a custom implementation of IConfigurationSource, but then I realized that I would have to duplicate the parsing logic already present in the FileConfigurationSource class.

The next thought was that I could create a new class that derives from FileConfigurationSource, and just use the new class as a proxy to pass in the config info instead of a string with the file path, but I couldn't see how to override the place where the file is loaded.

I checked out the SqlConfigurationSource QuickStart sample, but that again is not really what I think I need.

1

There are 1 answers

1
Josh E On BEST ANSWER

Here is the solution that I came up with to solve this issue:

I created a new class, XmlConfigurationSource, that derived from IConfigurationSource:

public class XmlConfigurationSource : IConfigurationSource
    {
        private string _xml;

        public XmlConfigurationSource(string xml)
        {
            _xml = xml;
        }
        //Other IconfigurationSource members omitted for clarity. 
        //Also, I'm not using them so I didn't implement them

        public ConfigurationSection GetSection(string sectionName)
        {
            //Since my solution is specific to validation, I'm filtering for that here.
            //This could easily be refactored for other EntLib blocks 
            //SerializableConfigurationSection object instead of XmlValidatorSettings
            if (sectionName != "validation")
                 return null;

             XmlValidatorSettings x = new XmlValidatorSettings(_xml.ToString());

             return x;            
         }
     }

The XmlValidatorSettings class was sort of the key to get this working. It's a very simple class deriving from ValidationSettings:

public class XmlValidatorSettings : ValidationSettings
    {
        public XmlValidatorSettings(string configXml)
        {
            XDocument doc = XDocument.Parse(configXml);
            DeserializeSection(doc.CreateReader());
        }
    }

To use this code you'll need to reference the EntLib common and validation DLL's. Hope other people benefit from this!