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.

app.config

settings.config

 

connections.config

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

Result:

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: ,

No comments:

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...