Pages

Tuesday, October 16, 2012

Implementing Custom Configuration Section - Part 1

.Net has made adding, and reading configurations from config files, app.config, web.config, machine.config, really simple. You can use appSettings sections to manage name value pair config, and connectionStrings sections to manage the connections strings to database. But, it has also provided a really simple way to create your own custom sections, and read it from the code. There are various reason why you want to do this way if appSettings does not fit your need. It's more readable, understandable. I will let you decide on the reasons :).

The code is really simple, so I will not go through it completely, however I will point out some interesting stuffs along the way. So, here you go. Here's a custom configuration section I want to build for.

<MyConfig
    Config1="Config1"
    Config2="Config2" 
    Config3="Config3"/>

And here's the class that can read the values from it:

using System.Configuration;
 
namespace BlogTestSample
{
    public class MyConfig : ConfigurationSection
    {
        private static MyConfig myConfig = ConfigurationManager.GetSection("MyConfig"as MyConfig;
 
        // private configuration properties
        [ConfigurationProperty("Config1", IsRequired = true)]
        private string config1 { get { return (stringthis["Config1"]; } }
 
        [ConfigurationProperty("Config2", IsRequired = true)]
        private string config2 { get { return (string)this["Config2"]; } }
 
        [ConfigurationProperty("Config3", IsRequired = true)]
        private string config3 { get { return (string)this["Config3"]; } }
 
        // public accessors
        public static string Config1 { get { return myConfig.config1; } }
        public static string Config2 { get { return myConfig.config2; } }
        public static string Config3 { get { return myConfig.config3; } }
    }
}

You also need to add the section name definition in configSections of the config file as follows:

<configSections>
    <section name="MyConfig" type="BlogTestSample.MyConfig, BlogTestSample"/>
</configSections>
The type has two params: the full namespace(namespace with class), and assembly name.

Some things to notice here:
  • The class inherits from ConfigurationSection. This basically tells the framework that it is a custom configuration section handler. 
  • The class name matches with the section name, but it doesn't have to. What we need to make sure is the parameter to GetSection() in fifth line must be same as the section name.
  • Each private string represents the configuration property in the config section. 
  • Each public string represents the getter for the private string.
  • If you have other types like int, decimal, just parse, and return the type back.
  • You can use the same format, if you have a config section inside a config section. In this case, your return type is the class that represents the config section.


No comments:

Post a Comment