RSS
Giga Web Solution - Gaetano Santonastaso

Binding Custom Configuration section to class in C#

Binding a Custom Configuration section to a class is an excellent way to decouple the program from its configurations and allows to easily Unit Test the configurations. In this post I am going to explain how to achieve this with a simple example.

Let's imagine we have a simple custom configuration section in our config file like the one below

<gigaWebSolutionSettings smtpServer="localhost" 
                                 systemAdministrator="gigapr@hotmail.com" 
                                 contactEmail="gigapr@hotmail.com" 
                                 pageSize="10"/>

That we register as

 <configSections>
    <section name="gigaWebSolutionSettings"
             type="GigaWebSolutionMVC3.Configuration.GigaWebSolutionConfigurations, 
                   GigaWebSolutionMVC3" />
  </configSections>

Where in 'type' the first parameter is the Namespace of the class that will be bound to the custom configuration section while the second is the name of the assembly that will contain the class.

At this point all we need is a public class that inherits from the System.Configuration.ConfigurationSection class. The latter allows to interprets and processes the settings that are defined in XML configuration elements in a specific section of a Web.config file.

namespace GigaWebSolutionMVC3.Configuration
{
    public class GigaWebSolutionConfigurations : ConfigurationSection
    {       
        [ConfigurationProperty("smtpServer", IsRequired = true)]
        public string SmtpServer
        {
            get { return (string)this["smtpServer"]; }
            set { this["smtpServer"] = value; }
        }

        [ConfigurationProperty("systemAdministrator", IsRequired = true)]
        public string SystemAdministrator
        {
            get { return (string)this["systemAdministrator"]; }
            set { this["systemAdministrator"] = value; }
        }

        [ConfigurationProperty("contactEmail", IsRequired = true)]
        public string ContactEmail
        {
            get { return (string)this["contactEmail"]; }
            set { this["contactEmail"] = value; }
        }

        [ConfigurationProperty("pageSize", IsRequired = true)]
        public int PageSize
        {
            get { return (int)this["pageSize"]; }
            set { this["pageSize"] = value; }
        }        
    }
}

As you can see each configuration is mapped to a class's property using the ConfigurationProperty attribute

[ConfigurationProperty("smtpServer", IsRequired = true)] 

Well that's all.....If you need any additional clarification or make any suggestion please don't hesitate to contact me.


Finally to initialize the class with the settings

var settings = (IGigaWebSolutionConfigurations)ConfigurationManager.GetSection("gigaWebSolutionSettings");




Aug5

Back To List