Send As SMS

Monday, June 20, 2005

Configuration files - mapping to code [Coding]

Introduction

I'm going to show another way where each appConfig key maped to class property. What we have from Microsoft to use configuration files:
  • Simple application configuration section, accessible via ConfigurationSettings class
  • Configuration Sections

In small applications, usually you are going to use 1st scenario.

Problems:

  • Impossible to track on start of application if all necessary information specified correctly.
  • Need to define a string constants for keys

I'm going to show a managed way to avoid both of these disadvantages and not using Configuration sections.

Goal

Idea is to use get a native class with properties mapped directly to configuration file and to put all dirty work to reflection and attributes.

Implementation

Source code with example is here - ConfigurationSolution.zip

ConfigurationHelper and attribute - Osypchuk.Configuration\ConfigurationHelper.cs

Derived class which define all keys as properties - Osypchuk.Configuration.TestConsole\Configuration.cs

Usage example - Osypchuk.Configuration.TestConsole\Main.cs

I have defined class Configurattion and uses ConfigKeyAttribute to apply it to every get method of properties. Base class looks for this attribute using StackTrace.

On loading, all class properties marked ConfigKeyAttribute with Mandatory = true checked to ensure it exist in config file.

Warning:

Virtual on each property is mandatory. Otherwise compiler generates get as inline. This causes that we would not be able to find ConfigKeyAttribute in stack trace.

Also please note that get method of property is marked with attribute, not property.


Applies to all dotnet languages: C#, VB.NET, C++.NET, J#

0 Comments:

Post a Comment

<< Home