web.config文件自定義配置節的使用方法

web.config文件自定義配置節的使用方法的一個簡單例子

用來演示的程序名爲MyApp,Namespace也是MyApp

1。編輯web.config文件

添加以下內容,聲明一個Section

<configSections>
   <section name="AppConfig" type="MyApp.AppConfig, MyApp" />
</configSections>  

聲明瞭一個叫AppConfig的Section

2。編輯web.config文件

添加以下內容,加入一個Section

<AppConfig>
  <add key="ConnectionString" value="this is a ConnectionString" />
  <add key="UserCount" value="199" />
</AppConfig> 

這個Section包括兩個 Key

3。從IConfigurationSectionHandler派生一個類,AppConfig

實現Create方法,代碼如下

public class AppConfig : IConfigurationSectionHandler
{
  static String m_connectionString = String.Empty;
  static Int32 m_userCount = 0;
  public static String ConnectionString
  {
   get
   {
    return m_connectionString;
   }
  }
  public static Int32 UserCount
  {
   get
   {
    return m_userCount;
   }
  }

  static String ReadSetting(NameValueCollection nvc, String key, String defaultValue)
  {
   String theValue = nvc[key];
   if(theValue == String.Empty)
    return defaultValue;

   return theValue;
  }

  public object Create(object parent, object configContext, XmlNode section)
  {
   NameValueCollection settings;
  
   try
   {
    NameValueSectionHandler baseHandler = new NameValueSectionHandler();
    settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);
   }
   catch
   {
    settings = null;
   }
  
   if ( settings != null )
   {
    m_connectionString = AppConfig.ReadSetting(settings, "ConnectionString", String.Empty);
    m_userCount = Convert.ToInt32(AppConfig.ReadSetting(settings, "UserCount", "0"));
   }
  
   return settings;
  }
}

我們把所有的配置都映射成相應的靜態成員變量,並且是寫成只讀屬性,這樣程序通過

類似AppConfig.ConnectionString就可以訪問,配置文件中的項目了

4。最後還要做一件事情

在Global.asax.cs中的Application_Start中添加以下代碼

System.Configuration.ConfigurationSettings.GetConfig("AppConfig");

這樣在程序啓動後,會讀取AppConfig這個Section中的值,系統會調用你自己實現的IConfigurationSectionHandler接口來讀取配置

參考信息二
Duwamish深入剖析-配置篇
http://www.microsoft.com/china/community/program/originalarticles/TechDoc/duwamish_con.mspx 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章