【问题标题】:How to define a basic custom configuration section?如何定义一个基本的自定义配置部分?
【发布时间】:2009-06-15 17:57:53
【问题描述】:

我有自己的自定义配置部分,但想创建一个新元素,其中包含简单的键/值。现在我有一个工作版本,但对于这样一个更简单的任务,似乎有很多代码。有没有改进的做事方式?

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

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

【问题讨论】:

标签: c# configuration settings


【解决方案1】:

我猜是这样的:

  <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】:

    手动执行此操作需要太多的努力。您可以让 Visual Studio 使用 Configuration Section Designer 加载项为您创建该部分。

    【讨论】:

    • 需要 Visual Stuiod 2008 或更高版本。
    • 其实VS 2010还不支持。 :o(
    猜你喜欢
    • 2010-10-25
    • 2010-11-12
    • 2013-09-17
    • 2011-07-04
    • 2012-12-12
    • 2013-09-21
    • 2014-01-19
    • 2011-10-02
    相关资源
    最近更新 更多