Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#

Custom Configuration Sections in .NET

Rate me:
Please Sign up or sign in to vote.
4.50/5 (18 votes)
28 Feb 2011CPOL3 min read 59K   52   11
Learn how to create custom configuration sections in .NET to help you simplify your application's configuration

Introduction

Inevitably, .NET developers will need to store application configuration data. Most often, developers choose to store this data in an XML Configuration File (.config). There are many different sections of this file that allow for the configuration of different areas of the application. One of these sections is the appSettings section. This section is a series of name-value pairs that can be used to add custom configuration data for an application. Over time, this section tends to become messy as an applications' functionality grows and complexity expands. In this article, we're going to look at how we can build custom configuration sections that will allow us to simplify our applications configuration data.

Using the Code

Here’s an example of an appSettings configuration section:

XML
<appsettings>
    <!--Misc Settings-->
    <add key="StandardHandlingFee" value="4.95" />
    <add key="PageSize" value="5" />

     ...
</appsettings>

Over time, the number of configuration items tends to grow and managing them can become confusing. What you end up with is a seemingly endless list of key value pairs that are difficult to manage. Additionally, the code required to access their values can start to get tedious.

C#
using System;
using System.Configuration;

namespace Before
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load Misc Settings
            decimal standardHandlingFee =
            Convert.ToDecimal(ConfigurationManager.AppSettings
            ["StandardHandlingFee"]);
            int pageSize = Convert.ToInt32
            (ConfigurationManager.AppSettings["PageSize"]);

            // ... do work ...
        }
    }
}

.NET has given the developers the ability to simplify this process by creating custom configuration sections. These custom configuration sections can help turn unstructured, untyped data into strongly-typed, straightforward elements. Basically, taking the almost meaningless key-value pairs and turning them into something more meaningful.

There are 3 pieces that makeup the custom configuration; a class that inherits from System.Configuration.ConfigurationSection; “registering” your configuration class in the configSections of your configuration file; and the XML configuration itself.

First is the class that handles how we access the configuration data.

C#
using System;
using System.Configuration;

namespace After.Configuration
{
    public class TestAppConfigProviderSection : ConfigurationSection
    {
        public static readonly TestAppConfigProviderSection Current =
        (TestAppConfigProviderSection)ConfigurationManager.GetSection
	("testAppConfigProvider");

        [ConfigurationProperty("StandardHandlingFee", DefaultValue = "4.95")]
        public decimal StandardHandlingFee
        {
            get { return (decimal)base["StandardHandlingFee"]; }
            set { base["StandardHandlingFee"] = value; }
        }

        [ConfigurationProperty("PageSize", DefaultValue = "10")]
        public int PageSize
        {
            get { return (int)base["PageSize"]; }
            set { base["PageSize"] = value; }
        }
    }
}

This class is pretty straightforward, but there are some key things to take note of. First, the main ConfigurationSection class must derive from the System.Configuration.ConfigurationSection class.

Also, within the TestAppConfigProviderSection class, I use a singleton style approach with the Current member. This helps make accessing the properties within the configuration section easy.

The configuration properties that the class is exposing should use the ConfigurationProperty attribute. The name that gets passed in this attribute should match the attribute name in the configuration file.

“Registering” our configuration section is done by adding a section in the configSections of the application’s .config file. The XML configuration is restructured to match how it is defined in our class. Here’s the new .config file after being refactored.

XML
<configuration>
  <configSections>
    <section name="testAppConfigProvider" 
	type="After.Configuration.TestAppConfigProviderSection, After"/>
  </configSections>
  <testAppConfigProvider StandardHandlingFee="4.95" PageSize="10" />
</configuration>

Here’s our example code again, but using the custom configuration sections:

C#
using System;
using After.Configuration;

namespace After
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load Misc Settings
            decimal standardHandlingFee =
            TestAppConfigProviderSection.Current.StandardHandlingFee;
            int pageSize = TestAppConfigProviderSection.Current.PageSize;

            // ... do work ...
        }
    }
}

It is also possible to load the custom configuration sections from an external file like so:

XML
<configuration>
  <configSections>
    <section name="testAppConfigProvider"
    type="After.Configuration.TestAppConfigProviderSection, After"/>

  </configSections>
  <testAppConfigProvider configSource="testApp.config" />
</configuration>

Where testApp.config looks like this:

XML
<testAppConfigProvider StandardHandlingFee="4.95" PageSize="10" />

One important note on using this method, you must make sure that you change the Copy to Output Directory property on the new .config file to either ‘Copy if newer’ or ‘Copy always’. Otherwise, the file won’t get copied to the projects bin directory and the ConfigurationManager won’t be able to load the file.

The benefits of using a custom configuration section handler are significant. Using the handler code is pretty straightforward and gives you less clutter in the appSettings as well as strong typing of your configuration elements.

History

  • 28th February, 2011: Initial post
  • 28th February, 2011: Article updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Software Developer

Comments and Discussions

 
GeneralGood introduction Pin
tgrt7-Sep-14 14:47
tgrt7-Sep-14 14:47 
QuestionHow to deal with dll in sub folder? Pin
Erik Vullings6-Jan-12 21:33
Erik Vullings6-Jan-12 21:33 
GeneralMy vote of 5 Pin
Monjurul Habib2-Apr-11 10:44
professionalMonjurul Habib2-Apr-11 10:44 
QuestionIs there something new here ? Pin
Yet Another XCoder9-Mar-11 3:19
Yet Another XCoder9-Mar-11 3:19 
GeneralDiving further Pin
John Whitmire8-Mar-11 7:16
professionalJohn Whitmire8-Mar-11 7:16 
GeneralMy vote of 5 Pin
Manfred Rudolf Bihy28-Feb-11 23:36
professionalManfred Rudolf Bihy28-Feb-11 23:36 
GeneralMy vote of 5 Pin
Tieske828-Feb-11 21:40
professionalTieske828-Feb-11 21:40 
Generalnice article Pin
BillW3328-Feb-11 3:57
professionalBillW3328-Feb-11 3:57 
GeneralMy vote of 5 Pin
Paulo Zemek28-Feb-11 3:41
mvaPaulo Zemek28-Feb-11 3:41 
GeneralRe: My vote of 5 Pin
Pete Mourfield28-Feb-11 3:49
Pete Mourfield28-Feb-11 3:49 
GeneralRe: My vote of 5 Pin
Paulo Zemek28-Feb-11 3:51
mvaPaulo Zemek28-Feb-11 3:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.