Domanda

I'm having trouble finding/figuring out how to map the following custom config section:

<section>
    <collection1>
        <subitem1 ... />
        <subitem1 ... />
    </collection1>
    <collection2>
        <subitem2 ... />
        <subitem2 ... />
    </collection2>
</section>

For a single sub collection, the following could would work:

public class Section : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(SubItem1Collection), AddItemName = "collection1")]
    public SubItem1Collection Collection1
    {
        get { return (SubItem1Collection)this[string.Empty]; }
        set { this[string.Empty] = value; }
    }
}

When I try to add the second collection, it wont run.

public class Section : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(TemplateCollection), AddItemName = "collection1")]
    public SubItem1Collection Collection1
    {
        get { return (SubItem1Collection)this[string.Empty]; }
        set { this[string.Empty] = value; }
    }

    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(SubItem2Collection), AddItemName = "collection2")]
    public SubItem2Collection Collection2
    {
        get { return (SubItem2Collection)this[string.Empty]; }
        set { this[string.Empty] = value; }
    }
}

The error is:

Unable to cast object of type 'SubItem1Collection' to type 'SubItem2Collection'.

The error is obviously in the indexer this[string.Empty];. Can anybody point me in the right direction on this?

È stato utile?

Soluzione

You cannot have two default collections. To have configuration classes matching your xml sample, you will have to assign the names "collection1" and "collection2" respectively instead of just "" and set IsDefaultCollection to false in the ConfigurationProperty attributes, and set the AddItemName to "subitem1" and "subitem2" for the ConfigurationCollection attributes. Also fix what @thymine pointed out about the type of the second collection.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top