代码之家  ›  专栏  ›  技术社区  ›  Pure.Krome

无法在自定义.config节中读取

  •  3
  • Pure.Krome  · 技术社区  · 15 年前

    注:这与此非常相似 SO question 但是我需要更多的帮助。

    我正在尝试在.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 { .. }
    }
    

    Kewl。现在,当我执行以下操作时……

    var whatever = ConfigurationManager.GetSection("foos") 引发以下异常:

    创建时出错 的配置节处理程序 FOOS:类型 'ackbar.mvc.models.foos.fooCollection' 不从继承 “System.Configuration.IConfigurationSectionHandler”。

    有人能帮我吗?我不想将集合包装在父节中。

    干杯:

    2 回复  |  直到 6 年前
        1
  •  2
  •   Mark Seemann    15 年前

    必须 实现一个 IConfigurationSectionHandler . 没办法。

    但是,您可以 FooCollection 也实现这个接口。

    这个 IsDefaultCollection 属性属性也可以派上用场。

        2
  •  0
  •   Jeff Mercado    6 年前

    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
    }
    
    推荐文章