代码之家  ›  专栏  ›  技术社区  ›  David

如何定义基本的自定义配置部分?

  •  5
  • David  · 技术社区  · 15 年前

    我有自己的自定义配置部分,但希望创建一个包含简单键/值的新元素。现在我有了一个有效的版本,但是对于这样一个简单的任务来说,它似乎有很多代码。有没有更好的做事方式?

    下面是我的配置和自定义配置类的剥离版本。

    Web.CONFIG

    <myRootNode>
        <myNode>
            <add key="a" value="" />
            <add key="b" value="" />
            <add key="c" value="" />
            ...
        </myNode>
        ...any other nodes
    </myRootNode>
    

    自定义配置类

    public class MyRootNode : ConfigurationSection
    {
        [ConfigurationProperty("myNode")]
        public MyNodeElement MyNode
        {
            get { return (MyNodeElement)this["myNode"]; }
        }
    }
    
    [ConfigurationCollection(typeof(BaseElement), AddItemName = "add")]
    public class MyNodeElement : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new BaseElement();
        }
    
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((BaseElement)element).Key;
        }
    
        public BaseElement this[int index]
        {
            get { return this.BaseGet(index) as BaseElement; }
        }
    }
    
    public class BaseElement : ConfigurationElement
    {
        [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
        public string Key
        {
            get { return this["key"].ToString(); }
        }
    
        [ConfigurationProperty("value", IsRequired = true)]
        public string Value
        {
            get { return this["value"].ToString(); }
        }
    }
    
    2 回复  |  直到 12 年前
        1
  •  10
  •   abatishchev Karl Johan    12 年前

    我想是这样的:

      <configSections>
          <section name="validationXsds"  type="System.Configuration.DictionarySectionHandler, System" />
      </configSections>
    
    
      <validationXsds>
        <add key="http://schemas.xmlsoap.org/soap/envelope/" value="http://dev.ei.directv.com/schemas/xmlsoap/envelope.xsd"/>
        <add key="http://schemas.xmlsoap.org/soap/encoding/" value="http://dev.ei.directv.com/schemas/xmlsoap/encoding.xsd"/>
        <add key="http://ei.directv.com/schemas/envelope/v3_0" value="http://dev.ei.directv.com/schemas/envelope/v3.0/Envelope.xsd"/>
      </validationXsds>
    
    IDictionary xsds = (IDictionary)WebConfigurationManager.GetSection("validationXsds"); 
    

    更新:在.NET 4.0中,我正在使用

     type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"
    
        2
  •  6
  •   John Rasch    15 年前

    手动执行此操作需要付出太多的努力。您可以让Visual Studio使用 Configuration Section Designer 加入进来。