2010-05-19 114 views
1

应用程序将配置数据存储在配置文件的自定义部分中。这些信息将在整个应用程序中使用。配置文件读取。最佳实践

现在我使用的辅助静态类来提供这样的访问(一些代码省略或简化):

[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 %> 

你觉得它是什么?我觉得它可用,因为它保持代码简单,但也困惑,因为IConfigurationSectionHandler已被弃用,因为.NET Framework 2.0

回答

1

那么,原则上,我认为这个概念没有错。

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

+0

对不起,我已经有了静态实例访问器(Current)。这是你提到的吗? – 2010-05-19 08:32:00

+0

@Andrew - 你这样做。我今晚离开了我的比赛,失去了显而易见的一面。好的,是的,我没有看到你做这件事的方式有什么问题,我用我的ConfigurationSections做了同样的事情。 – 2010-05-19 09:03:06

+0

好的。您如何看待Franci Penov建议的自定义配置节类? – 2010-05-19 09:36:56

2
+0

嗯,有趣的:)我会尝试重构 – 2010-05-19 06:10:57

+0

好了,终于我决定不重构,我将不得不实施如此多的特性。与我在这些日子使用的方法中的自动属性相比,验证的好处并不那么显着。 – 2010-05-19 08:29:03

+0

这是您的选择。但是,IConfigurationSectionHandler已被弃用,正如您自己提到的一样,可能会在将来版本的.Net框架中删除。我同意现在担心的事情可能会在一年内崩溃,但似乎有点过分,但如果您开始使用上述实施模式,那么最终会导致最终需要更改的模式。现在不妨做。 – 2010-05-19 16:16:56