Using web.config for custom configuration settings

Posted on 10:13am 1/22/2009 by Bruno Silva in .NET, ASP.NET, Programming, Web

If you are an ASP.NET developer you must be familiar with web.config. Something that maybe you haven’t tried yet is to create custom configuration sections to store you application specific settings. Bellow you can see a web.config file that uses a custom configuration section. In the configuration/configSections element you must define which class is responsible for handling your configuration section. Then you can add your custom settings to the file as shown bellow.

The usage of your settings is shown bellow. The configuration section handler class is used in order to access the configuration properties.

I’ve shown you the usage of a class called SiteSettings, but how does it’s definition look? It is a class that inherits the ConfigurationSection class. The configuration section properties are defined by adding public properties that correspond to Configuration Elements. While adding these properties you can define the name of the XML node that you will use in the web.config file and either if the property is required or not. In the example bellow you can see the Singleton design pattern in order do avoid creating several instances of the class and loading the section from the configuration file each time I access the values.

In this example, we only have one configuration property. It is defined in the class bellow. It corresponds to a contact information. Each property of this class correspond to an XML attribute, and by using annotations you can define the name of the XML attribute, it’s default value, if it is required and even add validators such as regular expression validators. You can use several variable types such as strings, integers and event enumerables.

By using custom configuration settings this way instead of accessing ConfigurationManager.AppSettings as a dictionary of string values you get intellisense while using configuration settings, and best of all, automatic validation of the types, constraints and structure of the settings (checked when the settings are accessed for the first time).

The full demo project is available for download. I hope it gets useful to you.


One Response to “Using web.config for custom configuration settings”


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© Bruno Silva | Powered by Wordpress