.NET Settings Framework

New Release

.NET Settings Framework 2.0.0-beta1 is out, with support for .NET Core, a unified library, fresh new APIs,and a new home on BitBucket.

The rest of the documentation below applies for the old 1.x release. If you are starting a new project, go for v2 instead.

Overview

The .NET Settings Framework is a small library that makes it easy to work with application settings. In the simplest case, it may be used to read AppSettings from an App.config or Web.config file; but it is easy to extend this functionality to databases and other arbitrary sources.

This framework was originally released as a proof of concept with this article,  which explains the motivation and design of the library. Since then it has continued to evolve, and is now available on NuGet under the following packages:

Features

  • Concise retrieval of settings
  • Strongly typed
  • Ability to specify default values, or use the default value of the type
  • Supports dependency injection, and is testable
  • Supports AppSettings, Environment Variables, and arbitrary sources
  • Supports basic types, enums, and nullables
  • Asynchronous retrieval
  • ConfigSection support

Prerequisites

  • Dandago.Settings – requires .NET Framework 4.0
  • Dandago.AsyncSettings – requires .NET Framework 4.5, and Dandago.Settings

Where to get it

It is easy to add the .NET Settings Framework to your project. Just install Dandago.Settings via NuGet. If you’re planning to retrieve settings asynchronously (e.g. from a database), install Dandago.AsyncSettings as well.

The source code is available on BitBucket as follows:

Example Usages

First, install Dandago.Settings via NuGet:

dandago.settings-nuget

Add a using statement:

using Dandago.Settings;

Now, let’s assume we have these AppSettings in a configuration file:

    <appSettings>
        <add key="timeoutInMilliseconds" value="5000" />
        <add key="enabled" value="true" />
    </appSettings>

To read AppSettings, this is a quick-and-dirty setup:

            var reader = new AppSettingReader();
            var provider = new ConfigKeyProvider(reader);

The reader is responsible for actually reading the raw setting from source, while the provider takes care of validation, conversion and default values. This separation allows the reader to be easily mocked in unit tests.

Reading individual AppSettings is easy:

            int timeout = provider.Get<int>("timeoutInMilliseconds", 3000); // 5000
            bool enabled = provider.Get<bool>("enabled", false); // true

If the AppSettings don’t exist or cannot be converted, the default values (second parameter above) apply:

            int timeout = provider.Get<int>("nonExistentKey", 3000); // 3000

You can omit the default value entirely, and the default value for the type will apply:

            int timeout = provider.Get<int>("nonExistentInt"); // 0
            bool enabled = provider.Get<bool>("nonExistentBool"); // false
            string name = provider.Get<string>("nonExistentString"); // null

AppSettingsReader implements the interface IConfigKeyReader. If you want to read settings from an arbitrary source (e.g. a database), just create your own implementation of IConfigKeyReader. Here’s a simple example:

    public class MemorySettingReader : IConfigKeyReader
    {

        public string Read(string key)
        {
            switch(key)
            {
                case "timeoutInMilliseconds":
                    return "5000";
                case "enabled":
                    return "true";
                default:
                    return null;
            }
        }
    }

For certain sources (e.g. databases) it makes sense to retrieve settings asynchronously. For that you can install the Dandago.AsyncSettings NuGet package, and use async equivalents of the classes and interfaces described above:

            var reader = new AsyncAppSettingReader();
            var provider = new AsyncConfigKeyProvider(reader);

            int timeout = await provider.GetAsync<int>("timeoutInMilliseconds", 3000);
            bool enabled = await provider.GetAsync<bool>("enabled", false);

The interfaces in the .NET Settings Framework make it easy both to test your code (e.g. by mocking the reader part) and to use dependency injection.

As from version 1.2, you can now also use the .NET Settings Framework to read ConfigSections. ConfigSections are a more organized way of handling application settings, and provide many of the benefits provided by the .NET Settings Framework (e.g. strong typing, default values). However, like with AppSettings, code that retrieves them directly is tricky to test. Say we have the following config section:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

<section name="personConfig" type="Dandago.Settings.ConsoleTestApp.PersonConfig, Dandago.Settings.ConsoleTestApp" />
  </configSections>
  <!-- ... -->
  <personConfig name="Daniel" age="27" />
</configuration>

To read ConfigSections, we use a special reader. A provider is not necessary, since its function is already provided by the ConfigSection itself:

            var configSectionReader = new ConfigSectionReader();
            var personConfig = configSectionReader.GetSection<PersonConfig>("personConfig");

Version 1.3 adds support for reading environment variables. It works just like for AppSettings, except that you use an EnvironmentVariableReader instead:

            var environmentVariableReader = new EnvironmentVariableReader();
            var environmentVariableProvider = new ConfigKeyProvider(environmentVariableReader);
            var tmp = environmentVariableProvider.Get<string>("TMP", "C:\\temp");

Terminology

  1. ConfigKey – a single setting.
  2. ConfigSection – a block of related settings.
  3. ConfigKeyReader – facilitates reading raw settings directly from their source.
  4. ConfigKeyProvider – gets a setting from a reader and performs validation, conversion and default values if necessary.

Release History

1.4.0 – 29th March 2017

Added support for enums and nullables.

1.3.0.0 – 14th November 2015

Added support for reading environment variables.

1.2.0.0 – 5th July 2015

Added ConfigSection support.

1.1.0.0 – 4th July 2015

Initial release on NuGet. Separates the asynchronous part of the library into a separate package to allow pre-.NET 4.5 projects to use the non-asynchronous part.

1.0.0.0 – 15th February 2015, plus minor changes later

Initial proof of concept based on this article.

2 thoughts on “.NET Settings Framework”

Leave a Reply

Your email address will not be published. Required fields are marked *

"You don't learn to walk by following rules. You learn by doing, and by falling over." — Richard Branson