1 Feb
2005

Hacking IConfigurationSectionHandler

Note: This article assumes that you are familiar with and
standard usage of a System.Configuration.IConfigurationSectionHandler.

Looking to load test a data layer API lead me to Sean
McCormack
‘s Zanebug
I am quite impressed so far.  I am using the beta version of 1.4.4 and it seems
very capable.

There is a feature that Sean says he will put into the release version that is currently
lacking, and that is the ability for the Unit Tests assemblies to read configuration
data from a .config file.  I have found a work around that I really like based
on a pattern that I learned from Matt Berther. 

I went ahead and implemented a standard .config file with my own configuration section
like so:

<configuration> <configSections> <section name="Healthwise" type="Healthwise.Testing.Lib.HWConnectXmlCoreApi.Test.Config.TestConfigSectionHandler,
Healthwise.Testing.Lib.HWConnectXmlCoreApi.Test" /> </configSections> </configuration> 

And then I implement a standard System.Configuration.IConfigurationSectionHandler class
with a Create() method, thusly:

1public object Create(object parent, object configContext,
System.Xml.XmlNode section) 2{ 3 Configuration
config = new Configuration(); 4 5 this.LoadConfig(
config, section ); 6 7 return config; 8}

I do all loading of my Configuration object in my LoadConfig(
Configuration, XmlNode )
function because I want to be able to access that
capability from my other CreateFromFile() method.

1public Configuration
CreateFromXmlFile() 2{ 3 Configuration
config = new Configuration(); 4 5 //
manually pick up the config file 6 XmlDocument
xml = new XmlDocument(); 7 xml.Load( this.GetConfigFilePath()
); 8 9 //
get the salient node and proceed as though I am Create() 10 this.LoadConfig(
config, xml.SelectSingleNode("/configuration/Healthwise")
); 11 12 return config; 13}

Now, I add a static accessor method to my Configuration class
that will return a valid Configuration whether the SestionHandler is invoked from
via the .Net configuration plumbing or manually.

1public static Configuration
GetInstance() 2{ 3 Configuration
config = System.Configuration.ConfigurationSettings.GetConfig( "Healthwise" ) as Configuration; 4 if(
config == null ) 5 { 6 TestConfigSectionHandler
handler = new TestConfigSectionHandler(); 7 config
= handler.CreateFromXmlFile(); 8 } 9 10 return config; 11}

This allows me to use the following code inside my [Test]
method without caring how the Configuration object gets filled instanciated.

1Configuration
config = Configuration.GetInstance();

Not bad, eh?

>>