10

我正在尝试为 .NET4 应用程序编写一个非常简单的自定义配置部分。我的目标是这样的:

<configuration>
  <configSections>
    <section name="myServices" type="My.ConfigSection, My.Assembly" />
  </configSections>
  <myServices>
    <add name="First" />
    <add name="Second" />
  </myServices>
</configuration>

但是,ConfigurationErrorsException当我调用ConfigurationManager.GetSection("myServices"). 我已经盯着它看了一段时间,但还没有弄清楚我做错了什么。下面是我的代码。它是三个类ConfigSectionMyServiceSettingsCollectionMyServiceSettings

首先是代表整个配置部分的类。它有一个无名的默认类型集合MyServiceSettingsCollection。该IsDefaultCollection属性应该允许我从根元素直接“添加”到我的集合中。

public sealed class ConfigSection : ConfigurationSection
{
  private static readonly ConfigurationProperty _propMyServices;

  private static readonly ConfigurationPropertyCollection _properties;

  public static ConfigSection Instance { get { return _instance; } }

  static ConfigSection()
  {
    _propMyServices = new ConfigurationProperty(
          null, typeof(MyServiceSettingsCollection), null,
          ConfigurationPropertyOptions.IsDefaultCollection);
    _properties = new ConfigurationPropertyCollection { _propMyServices };
  }

  [ConfigurationProperty("", IsDefaultCollection = true)]
  public MyServiceSettingsCollection MyServices
  {
    get { return (MyServiceSettingsCollection) base[_propMyServices]; }
    set { base[_propMyServices] = value; }
  }

  protected override ConfigurationPropertyCollection Properties
  { get { return _properties; } }
}

接下来是集合类本身。它是类型AddRemoveClearMap

[ConfigurationCollection(typeof(MyServiceSettings),
    CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public sealed class MyServiceSettingsCollection : ConfigurationElementCollection
{
  public MyServiceSettings this[int index]
  {
    get { return (MyServiceSettings) BaseGet(index); }
    set
    {
      if (BaseGet(index) != null) { BaseRemoveAt(index); }
      BaseAdd(index, value);
    }
  }

  public new MyServiceSettings this[string key]
  {
    get { return (MyServiceSettings) BaseGet(key); }
  }

  protected override ConfigurationElement CreateNewElement()
  {
    return new MyServiceSettings();
  }

  protected override object GetElementKey(ConfigurationElement element)
  {
    return ((MyServiceSettings) element).Key;
  }
}

最后是集合中元素的类。目前,这个类只有一个属性,但以后会有更多(这使我无法使用NameValueSectionHandler)。

public class MyServiceSettings : ConfigurationElement
{
  private static readonly ConfigurationProperty _propName;

  private static readonly ConfigurationPropertyCollection properties;

  static MyServiceSettings()
  {
    _propName = new ConfigurationProperty("name", typeof(string), null, null,
                                          new StringValidator(1),
                                          ConfigurationPropertyOptions.IsRequired |
                                          ConfigurationPropertyOptions.IsKey);
    properties = new ConfigurationPropertyCollection { _propName };
  }

  [ConfigurationProperty("name", DefaultValue = "",
        Options = ConfigurationPropertyOptions.IsRequired |
                  ConfigurationPropertyOptions.IsKey)]
  public string Name
  {
      get { return (string) base[_propKey]; }
      set { base[_propKey] = value; }
  }

  protected override ConfigurationPropertyCollection Properties
  { get { return properties; } }
}
4

3 回答 3

12

好的,我找到了看似随机的修复。而不是这个:

[ConfigurationProperty("", IsDefaultCollection = true)]
public ProvisiorServiceSettingsCollection ProvisiorServices
{ ... }

你应该使用:

[ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
public ProvisiorServiceSettingsCollection ProvisiorServices
{ ... }

不知道两者之间有什么区别。对我来说,它们看起来非常相似……或者至少,没有任何迹象表明为什么其中一个比另一个更受欢迎。

于 2011-08-15T15:18:39.733 回答
4

因为我花了很多时间在这上面,我想我会添加一个我刚刚在这个提交中实现的真实世界的例子:https ://github.com/rhythmagency/formulate/commit/4d2a95e1a82eb6b3500ab0869b8f8b15bd3deaa9

这是我的 web.config 目标(我能够实现):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="formulateConfiguration">
      <section name="templates" type="formulate.app.Configuration.TemplatesConfigSection, formulate.app" requirePermission="false"/>
    </sectionGroup>
  </configSections>
  <formulateConfiguration>
    <templates>
      <template name="Responsive" path="~/Views/Formulate/Responsive.Bootstrap.Angular.cshtml" />
    </templates>
  </formulateConfiguration>
</configuration>

这是最高级别的“模板”配置部分的类:

namespace formulate.app.Configuration
{

    // Namespaces.
    using System.Configuration;


    /// <summary>
    /// A configuration section for Formulate templates.
    /// </summary>
    public class TemplatesConfigSection : ConfigurationSection
    {

        #region Properties

        /// <summary>
        /// The templates in this configuration section.
        /// </summary>
        [ConfigurationProperty("", IsDefaultCollection = true)]
        [ConfigurationCollection(typeof(TemplateCollection), AddItemName = "template")]
        public TemplateCollection Templates
        {
            get
            {
                return base[""] as TemplateCollection;
            }
        }

        #endregion

    }

}

这是下一层,集合类:

namespace formulate.app.Configuration
{

    // Namespaces.
    using System.Configuration;


    /// <summary>
    /// A collection of templates from the configuration.
    /// </summary>
    [ConfigurationCollection(typeof(TemplateElement))]
    public class TemplateCollection : ConfigurationElementCollection
    {

        #region Methods

        /// <summary>
        /// Creates a new template element.
        /// </summary>
        /// <returns>The template element.</returns>
        protected override ConfigurationElement CreateNewElement()
        {
            return new TemplateElement();
        }


        /// <summary>
        /// Gets the key for an element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>The key.</returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as TemplateElement).Name;
        }

        #endregion

    }

}

这是最深层次的类(单个模板):

namespace formulate.app.Configuration
{

    //  Namespaces.
    using System.Configuration;


    /// <summary>
    /// A "template" configuration element.
    /// </summary>
    public class TemplateElement : ConfigurationElement
    {

        #region Constants

        private const string DefaultPath = "~/*Replace Me*.cshtml";

        #endregion


        #region Properties

        /// <summary>
        /// The name of the template.
        /// </summary>
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return base["name"] as string;
            }
            set
            {
                this["name"] = value;
            }
        }


        /// <summary>
        /// The path to this template.
        /// </summary>
        /// <remarks>
        /// Should start with "~" and end with ".cshtml".
        /// </remarks>
        [ConfigurationProperty("path", IsRequired = true, DefaultValue = DefaultPath)]
        [RegexStringValidator(@"^~.*\.[cC][sS][hH][tT][mM][lL]$")]
        public string Path
        {
            get
            {
                var result = base["path"] as string;
                return result == DefaultPath ? null : result;
            }
            set
            {
                this["path"] = value;
            }
        }

        #endregion

    }

}

对我来说重要的是在 IsDefaultCollection 中有空字符串ConfigurationPropertyAttribute并将 IsDefaultCollection 设置为 true。顺便说一句,我把我的配置放在一个看起来像这样的外部文件中:

<?xml version="1.0" encoding="utf-8" ?>
<templates>
    <template name="Responsive" path="~/Views/Formulate/Responsive.Bootstrap.Angular.cshtml" />
</templates>

在这种情况下,我的 web.config 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="formulateConfiguration">
      <section name="templates" type="formulate.app.Configuration.TemplatesConfigSection, formulate.app" requirePermission="false"/>
    </sectionGroup>
  </configSections>
  <formulateConfiguration>
    <templates configSource="config\Formulate\templates.config"/>
  </formulateConfiguration>
</configuration>

想我会提到,以防其他人试图将其添加到外部文件中(外部文件中的根级项目与 web.config 中的外部化元素相同,这有点不直观)。

于 2016-02-23T17:06:21.790 回答
3

看来你错过了类似的东西

[ConfigurationProperty("urls", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(UrlsCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]

有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx

于 2011-08-15T15:07:49.580 回答