基础才是重中之重~用好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); }
结果如下:
分类:
其它 / ASP.NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示