Originally posted on: http://geekswithblogs.net/woodbase/archive/2013/04/04/custom-config-sectionndashboth-in-general-and-for-umbraco.aspx
There’re several reasons why you’d want to minimize changes in your web.config and why you’d want to seperate configurations to independent files.
First of all – and this is my personal opinion – you’d want to avoid bloating your files, both your classes and config files. It makes it easier to keep an overview of what goes on where and why…
That’s why I like the way I’ve seen it done by for example Examine for Umbraco. They add a new Section in configSections node in the web.config with their own configurtion classes. This allows them to add an Examine node that again points to an “external” config file. But best shown with some example code, so lets get to it…
So here’s my solution looks:
First I have my configuration classes (I’ve deviated from my own seperation principles here, and put two classes in one file)
woodbaseChimpMailer.cs
namespace WoodbaseMailer.BusinessLogic.Configuration
{
public class WoodbaseChimpMailer : ConfigurationSection
{
public static WoodbaseChimpMailer GetConfig()
{
return ConfigurationManager.GetSection("WoodbaseChimpMailer") as WoodbaseChimpMailer;
}[ConfigurationProperty("woodbaseMailer")]
public WoodbaseMailer WoodbaseMailer
{
get
{
return (WoodbaseMailer)this["woodbaseMailer"];
}
set
{ this["woodbaseMailer"] = value; }
}
}
public class WoodbaseMailer : ConfigurationElement
{
[ConfigurationProperty("mailChimpSecureKey", DefaultValue = "", IsRequired = true)]
public string MailChimpSecureKey
{
get
{
return this["mailChimpSecureKey"] as string;
}
}
}
}
Not much magic – just declaring a ConfigurationSection and a ConfigurationElement. The configSection has the element as a property, and the element has it’s own property and just one in my case.
web.config:
This is how it’s referenced in the web.config
<configSections>
...
<section name="WoodbaseChimpMailer" type="WoodbaseMailer.BusinessLogic.Configuration.WoodbaseChimpMailer" requirePermission="false" />
...
</configSections>
...
<WoodbaseChimpMailer configSource="config\WoodbaseChimpMailer.config" />
...
woodbaseChimpMailer.config
Noteworthy in the next section is that the ConfigSection must be contained here again. The node from the web.config that points out the file, must be in the file.
<WoodbaseChimpMailer>
<woodbaseMailer mailChimpSecureKey="*****************-us6" />
</WoodbaseChimpMailer>
and finaly loading it in the usercontrol:
var mcKey = WoodbaseMailer.BusinessLogic.Configuration.WoodbaseChimpMailer.GetConfig().WoodbaseMailer.MailChimpSecureKey;
Conclusion
Once you figure out how to set it up. You’ll see that it really isn’t rocket.
My issue now is only to make the entries in the web.config when installing, but that will be another post….