当节类型是不同的程序集时,ConfigurationManager.GetSection返回null

时间:2014-01-28 13:31:29

标签: c# configurationmanager

我正在尝试从app.config中的配置部分读取,该部分已通过对NServiceBus的引用添加。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="UnicastBusConfig"
                 type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
        <section name="MessageForwardingInCaseOfFaultConfig"
                 type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core" />
        <section name="TestConfig"
                 type="Console1.UnicastBusConfigSection, Console1" />
    </configSections>
    <startup>
        <supportedRuntime version="v4.0"
                          sku=".NETFramework,Version=v4.5" />
    </startup>
    <MessageForwardingInCaseOfFaultConfig ErrorQueue="error" />
    <UnicastBusConfig>
        <MessageEndpointMappings></MessageEndpointMappings>
    </UnicastBusConfig>
    <TestConfig>
        <MessageEndpointMappings></MessageEndpointMappings>
    </TestConfig>
</configuration>

我为UnicastBusConfig部分定义了以下类:

public class UnicastBusConfigSection : ConfigurationSection
{
    [ConfigurationProperty(MessageEndPointMappingsName)]
    [ConfigurationCollection(typeof(MessageEndPointMappingsCollection), AddItemName = "add")]
    public MessageEndPointMappingsCollection MessageEndPointMappings { get { return (MessageEndPointMappingsCollection)base[MessageEndPointMappingsName]; } }
}

public class MessageEndPointMappingsCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MessageEndPointMappingsElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((MessageEndPointMappingsElement)element).Messages;
    }

    public void Add(MessageEndPointMappingsElement element)
    {
        BaseAdd(element);
    }
}

public class MessageEndPointMappingsElement : ConfigurationElement
{
    [ConfigurationProperty("Messages", IsRequired = true)]
    public string Messages
    {
        get { return (string)this["Messages"]; }
        set { this["Messages"] = value; }
    }

    [ConfigurationProperty("Endpoint", IsRequired = true)]
    public string Endpoint
    {
        get { return (string)this["Endpoint"]; }
        set { this["Endpoint"] = value; }
    }
}

当我为UnicastBusConfig部分调用ConfigurationManager.GetSection时,它返回null,但对于TestConfig部分,我得到了一个objet,确定...

var unicastBusConfigSection = ConfigurationManager.GetSection("UnicastBusConfig") as UnicastBusConfigSection;
var unicastBusConfigSection = ConfigurationManager.GetSection("TestConfig") as UnicastBusConfigSection;

0 个答案:

没有答案