Patterns for Accessing App.config SettingsJan6

Friday, 6 January 2012 by haemoglobin

Here are some patterns I have used for accessing App.config settings which I’ve found to be quite clean. If you introduce an interface over top of the class you will also be able to stub it out for unit testing.

Consider the following application settings:

<appSettings>
  <add key="DelaySeconds" value="15"/>
  <add key="EndDate" value="2013-02-01 6:30pm"/>
</appSettings>

In code, timers usually require millisecond values over seconds so we do a conversion here using the Lazy object showing how any calculations can be done once and when required. We can then access these with the class below:

public class AppSettings
{
    private readonly Lazy<int> _delayMilliseconds;
    
    public AppSettings()
    {
        _delayMilliseconds = new Lazy<int>(() => GetMilliseconds("DelaySeconds"), true);
    }

    public int DelayMilliseconds
    {
        get { return _delayMilliseconds.Value; }
    }

    private int GetMilliseconds(string configSettingName)
    {
        var seconds = GetSetting<double>(configSettingName);
        return Convert.ToInt32(seconds * 1000);
    }

    public T GetSetting<T>(string key)
    {
        string value = ConfigurationManager.AppSettings[key];
        if (value != null)
        {
            try
            {
                var converter = TypeDescriptor.GetConverter(typeof(T));
                return (T)converter.ConvertFrom(value);
            }
            catch(Exception ex)
            {
                var logError = string.Format("Unable to convert configuration value for {0} to type {1}", key, typeof(T).Name); 
                Console.WriteLine(logError);
                Console.WriteLine(ex.ToString());
            }
        }

        return default(T);
    }
}

You can either wrap each setting in its own property or access it directly based on the string key as below:

var appSettings = new AppSettings(); 
Console.WriteLine(appSettings.DelayMilliseconds); 
Console.WriteLine(appSettings.GetSetting<DateTime>("EndDate"));

The output being as below:

15000
01/02/2013 18:30:00
Categories:   Development
Actions:   E-mail | Permalink | Comments
blog comments powered by Disqus

Powered by BlogEngine.NET 1.6.1.0 | Design by styleshout | Enhanced by GravityCube.net | 1.4.5 Changes by zembian.com | Adapted by HamishGraham.NET
(c) 2010 Hamish Graham. Banner Image (c) Chris Gin