Configuration sections for app.config/web.config. Useful to create. Hard to remember how to create. Here's a simple template.
Every now and then I find myself needing to create a custom configuration section for a .NET application or module that I’m building. It’s not something I do often enough to remember how to do it by heart though so I usually consult Google, only there I often find guides that are either to long and/or verbose or doesn’t quite match how I like to do it. So I end up digging up some of my old code where I’ve created a custom configuration section. While that works it takes more time than it should so I thought I’d help myself by posting a quick little guide here.
Creating a basic Configuration Section
Given the class below…
using System.Configuration;
namespace ConfigurableModule
{
public class Configuration : ConfigurationSection
{
public static Configuration GetConfiguration()
{
Configuration configuration =
ConfigurationManager
.GetSection("myConfigurableModule")
as Configuration;
if (configuration != null)
return configuration;
return new Configuration();
}
[ConfigurationProperty("message", IsRequired = false)]
public string Message
{
get
{
return this["message"] as string;
}
}
}
}
…and the following in our applications configuration file (app.config/web.config)…
<configuration>
<configSections>
<section name="myConfigurableModule" type="ConfigurableModule.Configuration, ConfigurableModule"/>
</configSections>
<myConfigurableModule message="Hello world!" />
<!-- Optionally other configuration -->
</configuration>
…we can get the Message property from the configuration like this:
string messageFromConfiguration
= ConfigurableModule.Configuration
.GetConfiguration().Message ;
Storing the configuration section in a separate file
We can move our configuration section to a separate file using the configSource attribute. To do that in the above example we change it like this:
<configuration>
<configSections>
<section name="myConfigurableModule" type="ConfigurableModule.Configuration, ConfigurableModule"/>
</configSections>
<myConfigurableModule configSource="myConfigurableModule.config" />
<!-- Optionally other configuration -->
</configuration>
The file myConfigurableModule.config should then look like this:
<myConfigurableModule
message="Hello world from a separate file!" />
Creating ConfigurationElements, ConfigurationElementCollections etc
The above is usually all I need, but if a more extensive configuration is needed, requiring separate elements etc there is a more extensive guide on MSDN.