對於小型項目來說,配置信息可以通過appSettings進行配置,而如果配置信息太多,appSettings顯得有些亂,而且在開發人員調用時,也不夠友好,節點名稱很容易寫錯,這時,我們有幾種解決方案
1 自己開發一個配置信息持久化類,用來管理配置信息,並提供面向對象的支持 2 使用.net自帶的configSections,將配置信息分塊管理,並提供實體類,便於開發人員友好的去使用它本文主要說說第二種方案,它由實體類,實體類工廠及配置文件三個部分,看代碼:
實體類設計:
1 namespace Configer 2 { 3 /// <summary> 4 /// 網站信息配置節點 5 /// </summary> 6 public class WebConfigSection : ConfigurationSection 7 { 8 /// <summary> 9 /// 網站名稱 10 /// </summary> 11 [ConfigurationProperty("WebName", DefaultValue = "", IsRequired = true, IsKey = false)] 12 public string WebName 13 { 14 15 get { return (string)this["WebName"]; } 16 set { this["WebName"] = value; } 17 } 18 /// <summary> 19 /// 網站域名 20 /// </summary> 21 [ConfigurationProperty("DoMain", DefaultValue = "", IsRequired = true, IsKey = false)] 22 public string DoMain 23 { 24 25 get { return (string)this["DoMain"]; } 26 set { this["DoMain"] = value; } 27 } 28 29 } 30 }
實體工廠類設計,主要用來生產實體配置信息
1 namespace Configer 2 { 3 /// <summary> 4 /// 網站配置信息工廠 5 /// </summary> 6 public class WebConfigManager 7 { 8 /// <summary> 9 /// 配置信息實體 10 /// </summary> 11 public static readonly WebConfigSection Instance = GetSection(); 12 13 private static WebConfigSection GetSection() 14 { 15 WebConfigSection config = ConfigurationManager.GetSection("WebConfigSection") as WebConfigSection; 16 if (config == null) 17 throw new ConfigurationErrorsException(); 18 return config; 19 } 20 } 21 }
而最后就是.config文件了,它有configSections和指定的sections塊組成,需要注意的是configSections必須位於configuration的第一個位置
1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3 <configSections> 4 <section name="WebConfigSection" type="Configer.WebConfigSection, test"/> 5 </configSections> 6 <connectionStrings> 7 <add name="backgroundEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\sqlexpress;Initial Catalog=background;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /> 8 </connectionStrings> 9 10 <WebConfigSection WebName="占占網站" DoMain="www.zhanzhan.com" /> 11 <appSettings> 12 <add key="site" value="www.zzl.com"/> 13 14 </appSettings> 15 </configuration>
以上三步實現后,我們就可以調用了,呵呵
1 static void Main(string[] args) 2 { 3 Console.WriteLine(System.Configuration.ConfigurationManager.AppSettings["site"]); 4 Console.WriteLine(WebConfigManager.Instance.DoMain); 5 Console.WriteLine(WebConfigManager.Instance.WebName); 6 }
