Simple app.config appSettings deserializer (with tree structure)

By | 2017-10-30

There are many ways to read configuraiton files in .Net. Using ConfigurationManager you can easily read for example appSettings section. But usually I want this to be in managed code. The solution often suggested is to create separate sections with a varying degree of manual work, field mapping and xml readers.

Many of the solutions also suggest that you read and convert the type from string on every access, which gives you an overhead if you access config variables a lot. So I figured I’d throw together something simple that works. A baseclass that supports a tree structure without all the hassle of creating sections, defining types and names, etc… It reads and converts the variables once at startup to avoid conversion overhead on every access of properties.

In short, Config.SmtpClient.Host  corresponds to appSettings value “SmtpClient.Hosts“. You can add as many levels as you like.

app.config with appSettings section

The config variable names corresponds to properties in the classes. When there is a hierarchy of classes the names in the path will be separated by a dot.

Creating the config object

Config = new ConfigModel();

The implementation

In the implementation of config model we can create a hierarchy of models. As long as they inherid DictionaryConfigReader  and override the mandetory base class constructor they will automatically read config variables corresponding to their name.



Leave a Reply