patkua@work

Treat your App.config like a global variable

I remember looking at a few codebases in C# and it surprised me how many people encapsulate some of their system well, yet treat their application configuration as a different thing. Many times I’ve seen code that looks like: ConfigurationSettings.AppSettings["DatabaseConnectionString"]; alongside the thing that is using it. In fact, I often see this code repeated in various parts of the system wherever anyone needs to draw on application configuration.

Global variables are bad
Most good programmers seem to realise that most global variables are bad, yet this is exactly what I think accessing the application configuration is like. If you want to change the way your configuration is loaded (i.e. programmatically or from a database) think of how many places you now need to change it, let alone how it effects the order in which you instantiate objects.

My advice: Separate the use of configuration from where it declared
I try to follow the pattern isolating the configuration into a single class depending on the access method, such as:

Each of these classes them implement several roles depending on what configuration they might provide such as:

Having smaller roles makes it clearer what sort of configuration is really needed for a particular consumer, and it allows me to change the decision about how that configuration is now provided to it. It enables me to do things like specify different environment configurations and do so in the method that I prefer.

Exit mobile version