【问题标题】:Unable to read in my custom .config section无法读取我的自定义 .config 部分
【发布时间】:2010-02-24 08:10:56
【问题描述】:

注意:这与SO question 非常相似,但我需要更多帮助。

我正在尝试在我的 .config 文件中创建以下部分,但在尝试访问此部分时出现异常。

.config 文件

<configSections>
    <section name="foos" type="Ackbar.Mvc.Models.Foo.FooCollection, Ackbar.Mvc" requirePermission="false"/>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" />
</configSections>

<foos>
    <add name="aaa" something="zzz"/>
    <add name="bbb" something="yyy"/>
    <add name="ccc" something="xxx"/>
</foos>

好的,所以这意味着我需要创建两个

public class FooCollection : ConfigurationElementCollection
{
    ... with my custom overrides, etc. ...
}

public class FooElement : ConfigurationElement
{
    [ConfigurationProperty("Name", IsRequired = true)]
    public string Name { .. }

    [ConfigurationProperty("Something ", IsRequired = true)]
    public string Something { .. }

    [ConfigurationProperty("IsDefault ", IsRequired = false, DefaultValue = false)]
    public bool IsDefault { .. }
}

科尔。现在,当我执行以下操作时......

var whatever = ConfigurationManager.GetSection("foos") 抛出以下异常:-

创建时出错 配置节处理程序 foos:类型 'Ackbar.Mvc.Models.Foos.FooCollection' 不继承自 'System.Configuration.IConfigurationSectionHandler'。

有人可以帮帮我吗?我不想将集合包装在父部分中。

干杯:)

【问题讨论】:

    标签: .net configuration configurationelement


    【解决方案1】:

    必须实现IConfigurationSectionHandler。没办法。

    但是,您也可以让您的FooCollection 实现该接口。

    IsDefaultCollection 属性属性也可能派上用场。

    【讨论】:

    • 知道了 :) _finally- 花了我很多时间。我会在我的开篇文章中发布一些代码来帮助其他人。干杯伙伴!
    • IConfigurationSectionHandler 自 .NET 1.1 起已被弃用。请改用ConfigurationSection 类。
    • @RoastBeast 你应该回答这个问题,试图找出object Create(object parent, object configContext, XmlNode section) 期望的内容是浪费时间,因为你可以更改继承的类型。
    【解决方案2】:

    FooCollection 不是一个部分,所以你应该让它扩展 ConfigurationSection

    尽管如此,您仍然需要创建 ConfigurationElementCollection 作为支持集合,您只需要以不同的方式连接它。我会用FooSection 来为该部分本身命名。

    <configSections>
        <section name="foos" type="Ackbar.Mvc.Models.Foo.FooSection, Ackbar.Mvc" requirePermission="false"/>
    </configSections>
    
    <foos>
        <add name="aaa" something="zzz"/>
        <add name="bbb" something="yyy"/>
        <add name="ccc" something="xxx"/>
    </foos>
    

    还有部分:

    public class FooSection : ConfigurationSection
    {
        [ConfigurationProperty("", IsDefaultCollection=true)]
        public FooCollection Foos => (FooCollection)this[""];
    
        // optionally add convenience accessors to the `Foos` collection
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-20
      • 2021-11-14
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      相关资源
      最近更新 更多