Here is a quick tip for those of you who load configuration file sections at runtime. This is an especially good tip for those of you who have a lot of custom configuration sections and want to keep from writing a lot of redundant code for each section type... Essentially, all you need to do is create a Generic Configuration Manager and place it on a commonly accessible library. Once created you can use this to create custom configuration section instances as well as native .NET sections such as connectionStrings, appSettings, etc... Here is an example:
This example assumes you are using Web.Config files but this can easily be extended to support App.Config files, and Assembly Configuration Files.
using System;
using System.Configuration;
using System.Web.Configuration;
using System.Web.Hosting;
/// <summary>
/// Configuration File interop helper
/// class. This will assist in accessing
/// configuration file information
/// </summary>
public static class ConfigurationFile
{
/// <summary>
/// Retrieves a configuration section
/// instance from a configuration file
/// search all available configuration
/// file types
/// </summary>
/// <typeparam name="TYPE">The type of
/// the configuration to be retrieved
/// </typeparam>
/// <param name="sectionName">The name
/// (e.g. xml path) to the section to
/// be retrieved. This field is case
/// sensitive since it targets XML
/// elements</param>
/// <returns>The requested section
/// instance or a default instance if
/// none was found</returns>
public static TYPE GetConfigSection<TYPE>(string sectionName)
{
Configuration appConfig;
try
{
//Open the application configuration file
appConfig =WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
}
catch (ArgumentException)
{
//Section could not be retrieved...
appConfig = null;
}
//Create an instance member to hold
//the retrieved section
ConfigurationSection returnConfig = null;
//If the config was openedn then try
//and get the section
if (appConfig != null)
returnConfig = appConfig.GetSection(sectionName);
//If the section was not retrieved
//create a default instance otherwise
//return what was loaded
if (returnConfig == null)
return Activator.CreateInstance<TYPE>();
else
return (TYPE)(object)returnConfig;
}
}
Tags: design patterns