In September of 2015 I wrote a more extensive blog post that covered this material. However, it covered a lot of other material and buried what I’m discussing here. If you want more information on how to make your configurations work with custom build configuration read “Configuration Notes”
You are writing a cool new application that needs some of its settings to be stored in a configuration file. Happily .NET has always provided a nice configuration subsystem. In general everybody knows how to use it.
What I’m going to point our here is that you don’t need to use appSettings for your configuration stuff. In my experience appSettings is a horrible place to put your configuration information because it becomes crowded with stuff.
The alternative requires no code and in fact is still appSettings but allows you to organize your settings to keep different components separated from each other. In my current project I need to store the names of tables in Azure Table Storage being used by the service. Here is what my configuration file looks like:
The secret sauce is in the type tag for our RescueServices section. The type, NameValueSectionHandler is the same type used for appSettings. You can verify this by finding the machine.config file and checking out how the sections are defined.
In order to access your configuration information you just need to write the following lines of code:
This is the only downside to not being in appSettings: configuration manager doesn’t provide a short cut. Instead you first have to ask for your section and tell it the type to use. For us we just use a NameValueCollection (same as appSettings) and we’re good to go. Once you have the collection you can go to town.
A truly lazy developer would create a base class that handles all of this so that all you must do is provide the name of the configuration section and it handles the rest. That is left as an exercise for the reader.