基础才是重中之重~用好configSections让配置信息更规范
生活随笔
收集整理的這篇文章主要介紹了
基础才是重中之重~用好configSections让配置信息更规范
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
對于小型項目來說,配置信息可以通過appSettings進行配置,而如果配置信息太多,appSettings顯得有些亂,而且在開發人員調用時,也不夠友好,節點名稱很容易寫錯,這時,我們有幾種解決方案
1 自己開發一個配置信息持久化類,用來管理配置信息,并提供面向對象的支持2 使用.net自帶的configSections,將配置信息分塊管理,并提供實體類,便于開發人員友好的去使用它本文主要說說第二種方案,它由實體類,實體類工廠及配置文件三個部分,看代碼:
實體類設計:
namespace Configer {/// <summary>/// 網站信息配置節點/// </summary>public class WebConfigSection : ConfigurationSection{/// <summary>/// 網站名稱/// </summary>[ConfigurationProperty("WebName", DefaultValue = "", IsRequired = true, IsKey = false)]public string WebName{get { return (string)this["WebName"]; }set { this["WebName"] = value; }}/// <summary>/// 網站域名/// </summary>[ConfigurationProperty("DoMain", DefaultValue = "", IsRequired = true, IsKey = false)]public string DoMain{get { return (string)this["DoMain"]; }set { this["DoMain"] = value; }}} }實體工廠類設計,主要用來生產實體配置信息
namespace Configer {/// <summary>/// 網站配置信息工廠/// </summary>public class WebConfigManager{/// <summary>/// 配置信息實體/// </summary>public static readonly WebConfigSection Instance = GetSection();private static WebConfigSection GetSection(){WebConfigSection config = ConfigurationManager.GetSection("WebConfigSection") as WebConfigSection;if (config == null)throw new ConfigurationErrorsException();return config;}} }而最后就是.config文件了,它有configSections和指定的sections塊組成,需要注意的是configSections必須位于configuration的第一個位置
<?xml version="1.0" encoding="utf-8"?> <configuration><configSections><section name="WebConfigSection" type="Configer.WebConfigSection, test"/></configSections><connectionStrings><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" /></connectionStrings><WebConfigSection WebName="占占網站" DoMain="www.zhanzhan.com" /><appSettings><add key="site" value="www.zzl.com"/></appSettings> </configuration>以上三步實現后,我們就可以調用了,呵呵
static void Main(string[] args){Console.WriteLine(System.Configuration.ConfigurationManager.AppSettings["site"]);Console.WriteLine(WebConfigManager.Instance.DoMain);Console.WriteLine(WebConfigManager.Instance.WebName);}結果如下:
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的基础才是重中之重~用好configSections让配置信息更规范的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET MVC 实现模式 - M
- 下一篇: Oracle undo表空间爆满的解决