2010-05-19 117 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