Unable to read in my custom .config section

5.4k views Asked by At

NOTE: this is very very similar to this SO question, but I need some more help.

i'm trying to make the following section in my .config file, but i get an exception when trying to access this section.

.config file

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

Ok, so this means i need to make two classes

classes

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

and

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. Now, when i do the following ....

var whatever = ConfigurationManager.GetSection("foos") is throws the following exception :-

An error occurred creating the configuration section handler for foos: Type 'Ackbar.Mvc.Models.Foos.FooCollection' does not inherit from 'System.Configuration.IConfigurationSectionHandler'.

Can someone please help me? I don't want to wrap the collection INSIDE a parent section.

Cheers :)

2

There are 2 answers

3
Mark Seemann On BEST ANSWER

You must implement an IConfigurationSectionHandler. No way around that.

However, you may be able to let your FooCollection implement that interface as well.

The IsDefaultCollection attribute property may also come in handy.

0
Jeff Mercado On

FooCollection is not a section, so you should have it extend ConfigurationSection.

Though, you'll still need to create the ConfigurationElementCollection as the backing collection, you just need to wire it up differently. I would name things a bit differently with FooSection for the section itself.

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

And the section:

public class FooSection : ConfigurationSection
{
    [ConfigurationProperty("", IsDefaultCollection=true)]
    public FooCollection Foos => (FooCollection)this[""];

    // optionally add convenience accessors to the `Foos` collection
}