配置文件读取。最佳实践

时间:2010-05-19 05:58:59

标签: .net api configuration

应用程序将配置数据存储在配置文件的自定义部分中。此信息在整个应用程序中使用。

现在我使用helper static class来提供这样的访问(省略或简化了一些代码):

[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));
    }
}

然后我像这样使用它

<%: WebSiteConfig.Current.Section1.Value1  %>
<%: WebSiteConfig.Current.Section1.Value2  %>
你怎么看?我发现它可用,因为它保持代码简单,但也因为.NET Framework 2.0以来不推荐使用IConfigurationSectionHandler而感到困惑

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

嗯,原则上,我认为这个概念并没有错。

更易于管理的实现可能是在配置部分中实现默认的静态实例访问器并使用它。