zoukankan      html  css  js  c++  java
  • VS2012 常用web.config配置解析之自定义配置节点

    在web.config文件中拥有一个用户自定义配置节点configSections,这个节点可以方便用户在web.config中随意的添加配置节点,让程序更加灵活(主要用于第三方插件的配置使用)

    自定义节点是一个XML格式的数据,我们可以在节点中灵活的配置自己的数据,下面是一个简单数据的例子

    1.先看一下web.config中的配置结构

      <configSections>
        <section name="modelsection" type="Amy.WebUI.Plugin.ConfigSections.ModelSectionHandler,Amy.WebUI"/>
      </configSections>
    
      <modelsection>
        <title>测试</title>
        <content>测试</content>
      </modelsection>
    

     2.为了实现自定义配置节点的解析,我们需要实现接口IConfigurationSectionHandler

        public class ModelSectionHandler : IConfigurationSectionHandler
        {
            /// <summary>
            /// 解析配置文件信息
            /// </summary>
            public object Create(object parent, object configContext, XmlNode section)
            {
                var json = section.ToJsonByJsonNet().GetJsonValue("modelsection");
    
                return json.ToObjectByJsonNet<ModelConfig>();
            }
        }
    

     3.ModelConfig类为了防止消耗IO资源,做了一个单例

        public class ModelConfig
        {
            private static ModelConfig instance;
            private static readonly object syncObject = new object();
    
            private ModelConfig() { }
    
            public static ModelConfig GetInstance()
            {
                if (instance == null)
                {
                    lock (syncObject)
                    {
                        if (instance == null)
                        {
                            instance = (Plugin.ConfigSections.ModelConfig)System.Configuration.ConfigurationManager.GetSection("modelsection");
                        }
                    }
                }
    
                return instance;
            }
    
    
            public string Title { get; set; }
    
            public string Content { get; set; }
        }
    

     4.读取数据,很简单及类的静态方法调用就OK;var config = Plugin.ConfigSections.ModelConfig.GetInstance();

  • 相关阅读:
    JVM学习笔记之认识JDK(一)
    C#发送邮件异常:根据验证过程,远程证书无效
    windows下使用mysql双机热备功能
    批处理实现mysql的备份
    WebApi FormData+文件长传 异步+同步实现
    Oracle中已知字段名查询所在的表名
    mstsc遇到CredSSP加密Oracle修正
    使用subgit进行svn迁移至git(branch,tags)
    使用guava进行对字符串的加锁
    使用spring-data-solr做solr客户端
  • 原文地址:https://www.cnblogs.com/amywechat/p/4897678.html
Copyright © 2011-2022 走看看