Pages

Wednesday, February 18, 2009

Generic, type safe Configuration Manager

I like to store lots of config data in the Web.Config and I get fed up with having to cast the ConfigSection to the concrete class:
MyConfigSectionHandler handler =
(MyConfigSectionHandler)
WebConfigurationManager.GetSection(sectionName);

So I've written a helper class where now you can use:
MyConfigSectionHandler config =
ConfigManager.Instance.GetSection<MyConfigSectionHandler>
(sectionName);

Here's the code - (I've implemented it as a Singleton for a reason I don't remember now):
public class ConfigManager
{
private static ConfigManager _instance;
private static object _lock = typeof(ConfigManager);

private ConfigManager()
{

}

/// <summary>
/// Gets a singleton instance.
/// </summary>
/// <value>The instance.</value>
public static ConfigManager Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new ConfigManager();
}

return _instance;
}
}
}

/// <summary>
/// Gets the section.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sectionName">Name of the section.</param>
/// <returns></returns>
public T GetSection<T>(string sectionName)
where T : class
{
return WebConfigurationManager.GetSection(sectionName) as T;
}
}

No comments: