zoukankan      html  css  js  c++  java
  • NET 自定义配置文件 Configuration

    说起.NET的配置文件,.NET的开发人员无人不知,无人不用,如下面的配置节点,基本上每个.NET开发的项目都会出现像下面的配置,出现在App.config或者Web.config中

    <connectionStrings> 
        <add name="DbConnectionString" connectionString="...."/>
    </connectionStrings>
    <appSettings>
        <add key="LogFilePath" value="c:/Logs/"/>
    </appSettings>

    一般的项目用NET提供的配置节点就已经够用了,但是如果项目的配置文件很多很多,appSettings就会出现大量的配置,基本上都是key和value的组合,如果再加上命名不易读,维护就会很麻烦,又或者你自己写了一个框架给别人用,需要定义符合自己的配置节点,所以有些时候我们需要自定义一些配置.

    其实NET已经提供了自定义配置的基类和一些接口,对创建自定义的配置已经非常方便了,下面就开始做几个简单的实例吧

    1. 创建一个控制台的项目 CustomConfigurationDemo,添加App.Config并且引用System.configuration dll

    2. 创建 CustomConfigurationFirst类继承ConfigurationSection,添加属性long Id, string Name,string FirstProperty,并且通过ConfigurationPropertyAttribute标记属性,第一个字符串为 配置文件中配置的属性名,DefaultValue为默认值,其他属性就不一一介绍了,可以参考ConfigurationPropertyAttribute的注释信息。

    public class CustomConfigurationFirst : ConfigurationSection
        {
            private static CustomConfigurationFirst setting;
            public static CustomConfigurationFirst Setting
            {
                get 
                {
                    if(setting == null)
                        setting = (CustomConfigurationFirst)ConfigurationManager.GetSection("firstCustomConfiguration");
                    return setting;
                }
            }
    
            [ConfigurationProperty("id", DefaultValue = "1", IsRequired = true)]
            public long Id
            {
                get { return (long)this["id"]; }
                set { this["id"] = value; }
            }
    
            [ConfigurationProperty("name", DefaultValue = "Lily", IsRequired = true)]
            public string Name 
            {
                get { return (string)this["name"]; }
                set { this["name"] = value; }
            }
    
            [ConfigurationProperty("firstProperty", DefaultValue = "Property1", IsRequired = true)]
            public string FirstProperty
            {
                get { return (string)this["firstProperty"]; }
                set { this["firstProperty"] = value; }
            }
        }

    我们自定义的配置创建好了,现在需要添加配置到App.config文件中,如下图所示,首先需要创建configSections,把自定义的节点加进去,name随便填写(填写的值将会与代码中的ConfigurationManager.GetSection("firstCustomConfiguration")名称对应),type需要填写自定义配置节点类的全名称和程序集

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="firstCustomConfiguration" type="CustomConfigurationDemo.CustomConfigurationFirst,CustomConfigurationDemo"/>
      </configSections>
    
      <firstCustomConfiguration id="12" name="name" firstProperty="property2"/>
      
    </configuration>

    一切准备就绪,用控制台程序打印出我们刚刚配置的属性看看吧!

     Console.WriteLine("----CustomConfigurationFirst---------------------");
     CustomConfigurationFirst settingFirst = CustomConfigurationFirst.Setting;
     Console.WriteLine("settingFirst.Id:" + settingFirst.Id);
     Console.WriteLine("settingFirst.Name:" + settingFirst.Name);
     Console.WriteLine("settingFirst.FirstProperty"+ settingFirst.FirstProperty);
     Console.WriteLine("--------------------------------------------------");
    

    运行结果如下,和我们配置文件中设置的值一样,是不是感觉很简单。

    3. 有时候我们需要在配置文件中加一些子节点,应该怎么做呢?

    先创建一个 UrlConfigurationElement:ConfigurationElement,在ConfigurationElement里面添加属性和在Section里面添加是一样的,然后我们创建一个CustomConfigurationSecond : ConfigurationSection,并创建一个属性的类型是UrlConfigurationElement的,如下图所示:

    [ConfigurationProperty("url")]
    public UrlConfigurationElement UrlElement
    {
          get { return (UrlConfigurationElement)this["url"]; }
          set { this["url"] = value; }
    }

     此时配置文件添加的配置为:

    <secondCustomConfiguration>
        <url name="baidu" url="http://www.baidu.com" />
    </secondCustomConfiguration>

     然后通过代码获取配置属性:

     Console.WriteLine("----CustomConfigurationSecond---------------------");
     CustomConfigurationSecond settingSecond = CustomConfigurationSecond.Setting;
     Console.WriteLine("settingSecond.UrlElement.Name:" + settingSecond.UrlElement.Name);
     Console.WriteLine("settingSecond.UrlElement.Url:" + settingSecond.UrlElement.Url);
     Console.WriteLine("--------------------------------------------------");

    输出结果为:与配置文件一样

    4. 以上是创建一个配置节点的情况,假如我们修改配置为

    <secondCustomConfiguration>
        <url name="baidu" url="http://www.baidu.com" />
        <url name="google" url="http://www.google.com" />
    </secondCustomConfiguration>

     此时就会报错 “元素 <url> 只能在此节中出现一次。”怎么样修改能支持上述的情况呢?

    NET为我们提供了ConfigurationElementCollection,创建UrlConfigurationElementCollection继承ConfigurationElementCollection,并且实现2个抽象方法

    public class UrlConfigurationElementCollection : ConfigurationElementCollection
        {
    
            protected override ConfigurationElement CreateNewElement()
            {
                return new UrlConfigurationElement();
            }
    
            protected override object GetElementKey(ConfigurationElement element)
            {
                return ((UrlConfigurationElement)element).Name;
            }
        }

    创建CustomConfigurationThird : ConfigurationSection

     [ConfigurationProperty("urls")]
     [ConfigurationCollection(typeof(UrlConfigurationElementCollection),AddItemName = "addUrl",ClearItemsName = "clearUrls", RemoveItemName = "RemoveUrl")]
     public UrlConfigurationElementCollection UrlElements
     {
         get { return (UrlConfigurationElementCollection)this["urls"]; }
         set { this["urls"] = value; }
     }

    配置文件为

    <thirdCustomConfiguration>
        <urls>
          <addUrl name="google" url="http://www.google.com" />
          <addUrl name="sina" url="http://www.sina.com" />
          <addUrl name="360buys" url="http://www.360buys.com" />
        </urls>
    </thirdCustomConfiguration>

     输出结果为:

    好了,这次就简单的介绍下自定义配置的入门,其实NET提供了很多其他复杂的功能,没有特别需求的话以上的三种自定义配置基本上就够用了,我认为是这样的,还有一点忘记说了,如果自定义配置节点太多的话可以配置sectionGroup,如果设置了分组name是必填项,代码获取配置的时候加上sectionGroup name就可以了,如:

     setting = (CustomConfigurationFirst)ConfigurationManager.GetSection("customGroup/firstCustomConfiguration");

     <configSections>
        <sectionGroup name="customGroup">
          <section name="firstCustomConfiguration" type="CustomConfigurationDemo.CustomConfigurationFirst,CustomConfigurationDemo"/>
        </sectionGroup>
        <section name="secondCustomConfiguration" type="CustomConfigurationDemo.CustomConfigurationSecond,CustomConfigurationDemo"/>
        <section name="thirdCustomConfiguration" type="CustomConfigurationDemo.CustomConfigurationThird,CustomConfigurationDemo"/>
      </configSections>
    
      <customGroup>
        <firstCustomConfiguration id="12" name="name" firstProperty="property2"/>
      </customGroup>

    想深入研究的话可以参考MSDN

    点击链接下载Demo

    支持why520crazy的创业产品Worktile
    Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
    https://worktile.com
  • 相关阅读:
    腾讯视频插入网页的代码;
    FW: 软件持续交付的诉求;
    TOGAF
    Windows WSL2 htop打开黑屏的问题解决
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='appts.xxx.com%20', port=443):
    sqlalchemy实现模糊查询
    jenkins过滤版本,可选择版本
    QML 布局之一:锚布局详解(各种例子)
    Qt Quick 常用控件:Button(按钮)用法及自定义
    The Common Order Operations of Dis Operation System (DOSS)
  • 原文地址:https://www.cnblogs.com/why520crazy/p/2791964.html
Copyright © 2011-2022 走看看