應用程序將配置數據存儲在配置文件的自定義部分中。這些信息將在整個應用程序中使用。配置文件讀取。最佳實踐
現在我使用的輔助靜態類來提供這樣的訪問(一些代碼省略或簡化):
[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
對不起,我已經有了靜態實例訪問器(Current)。這是你提到的嗎? – 2010-05-19 08:32:00
@Andrew - 你這樣做。我今晚離開了我的比賽,失去了顯而易見的一面。好的,是的,我沒有看到你做這件事的方式有什麼問題,我用我的ConfigurationSections做了同樣的事情。 – 2010-05-19 09:03:06
好的。您如何看待Franci Penov建議的自定義配置節類? – 2010-05-19 09:36:56