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();

posted @ 2015-10-21 14:26  荒古禁地  阅读(1004)  评论(0编辑  收藏  举报