The tale of the annoying read-only ConfigurationElement
One of the piece of code I disseminate on each project I work on is a lightweight factory builder. The idea is that you declare which interfaces are implemented by which types, or constructed by which builder. It's perfect for replacing all the types you abstract when unit testing, and put the responsibility of the dependency injection on the configuration file.
Here's a small example of how one would declare an interface as having a concrete implementation.
<factories> <factory interface-type="CaffeineIT.Blog.IConfigProvider, CaffeineIT.Blog.Demo" concrete-type="CaffeineIT.Blog.SettingsConfigProvider, CaffeineIT.Blog.Demo" /> </factories>
Very straightforward. From your code you initialize the type like so.
var myConfig = FactoryActivator.CreateInstance<IConfigProvider>();
The problem when unit testing my configuration sections is that they're read-only by default. That means I need to do some black magic swapping config files around when running my tests.
Well, it's not very well documented, but with the help of reflector, you discover the secret so many have kept to themselves. To make your ConfigurationElement read-write, override the SetReadOnly method and do nothing.
protected override void SetReadOnly() { //do nothing! }
I don't know about you but I feel like I'm cheating.