日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

基础才是重中之重~用好configSections让配置信息更规范

發(fā)布時間:2025/6/15 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基础才是重中之重~用好configSections让配置信息更规范 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

對于小型項目來說,配置信息可以通過appSettings進行配置,而如果配置信息太多,appSettings顯得有些亂,而且在開發(fā)人員調用時,也不夠友好,節(jié)點名稱很容易寫錯,這時,我們有幾種解決方案

1 自己開發(fā)一個配置信息持久化類,用來管理配置信息,并提供面向對象的支持2 使用.net自帶的configSections,將配置信息分塊管理,并提供實體類,便于開發(fā)人員友好的去使用它

本文主要說說第二種方案,它由實體類,實體類工廠及配置文件三個部分,看代碼:

實體類設計:

namespace Configer {/// <summary>/// 網站信息配置節(jié)點/// </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=&quot;Data Source=.\sqlexpress;Initial Catalog=background;Integrated Security=True;MultipleActiveResultSets=True&quot;" 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位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的基础才是重中之重~用好configSections让配置信息更规范的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。