.netconfiguration

Configuration file reading. Best practice


Application stores configuration data in custom section of configuration file. This information is used all over the application.

Nowadays I use helper static class to to provide access like this (some code omitted or simplified):

[XmlRoot("webSiteSection")]
public class WebSiteConfig : IConfigurationSectionHandler
{

    public static WebSiteConfig Current
    {
         get
         {          
             if (_current == null)
                _current = (WebSiteConfig) ConfigurationManager.GetSection("webSiteSection");

            return _current;
     }  
    }

    [XmlElement("section1")]
    public Section1 Section1 { get; set; }

    [XmlElement("section2")]
    public Section2 Section2 { get; set; }

    ...

    public object Create(object parent, object configContext, XmlNode section)
    {
        var serializer = new XmlSerializer(typeof(WebSiteConfig));
        return serializer.Deserialize(new XmlNodeReader(section));
    }
}

Then I use it like this

<%: WebSiteConfig.Current.Section1.Value1  %>
<%: WebSiteConfig.Current.Section1.Value2  %>

What do you think of it? I find it usable because it keeps code simple, but also confused as IConfigurationSectionHandler is deprecated since .NET Framework 2.0


Solution

  • Well, in principal, i see nothing wrong with the concept.

    A more manageable implementation may be to implement a default static instance accessor in your configuration section and use that.