28 May, 2011

.NET: How to externalize your configuration

At times you run into a situation where an “externalization” of your configuration files would be nice.

Not always is your host your “own” proces, but your code is being executed by some existing process (e.g. a service), and you do not want to “polute” this system’s native configuration with settings only you’re are requiring. Put in other words – settings that applies only to your own code and not to the hosting service.

How to do this?
In the below illustration, it is desired to provide connectionstrings from the outside as your own code (extension1.dll) apparently needs it. In addition to connectionstrings, it is also desired to supply appSettings from the outside.

external configuration

This is quite easily achieved as .NET’s configuration subsystem has had support for this since .NET 2.0.

To your hosting process, you need to tell the configuration subsystem that it should go looking for settings in another file. This is achieved by an attribute called configSource in the app.config file.





Do pay attention to the fact that these external files only contains xml-fragments. This is important, as the configuration system will fail to initialize otherwise.

Why is this so? The reason shall be found in the way the .NET configuration system merges these 3 files together in memory. It is analogous to the later transformation-configurations that came out in Visual Studio.

Anyway – to make use of this, you go the traditional way (this is just a sample to test out the configuration!). The beauty is that the hosting process is completely unaware of this “externalization”.

program code


Resulting process

Note1: This only works if your configuration files are located in the same folder (or subfolder) as the parent process.

Note2: The (native) configuration section you wish to provide from the outside, needs to have an attribute called ‘configSource’.

That’s all there is to it…

StackOverflow Tags: ,

1 comment:

Radley Co Tad said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...