当在不同的模块中解析时,Unity无法解析类型

本文关键字:Unity 类型 模块 | 更新日期: 2023-09-27 18:12:17

我目前正在使用unity容器和WCF服务开发PRISM应用程序。在模块中(使用WCF代理),我为WCF客户端注册了一个ChannelFactory,如下所示:

InstanceContext instanceContext = new InstanceContext(new TradingPlatformCallback());
unityContainer.RegisterType<DuplexChannelFactory<IGenericTradingInterface>, DuplexChannelFactory<IGenericTradingInterface>>(
    new ContainerControlledLifetimeManager(),
    new InjectionConstructor(
        instanceContext,
        "NetNamedPipeBinding_IGenericTradingInterface"));
DuplexChannelFactory<IGenericTradingInterface> factory = unityContainer.Resolve<DuplexChannelFactory<IGenericTradingInterface>>();
factory.Open();
IGenericTradingInterface test = factory.CreateChannel();
test.GetServerInformation();
factory.Close();
现在,一切都很好,所以我决定在另一个模块中使用这个ChannelFactory。下面是该模块的Initialize方法:
var test = unityContainer.Resolve<DuplexChannelFactory<IGenericTradingInterface>>();
test.Open();
var test2 = test.CreateChannel();
test2.GetServerInformation();
test.Close();
所以这段代码与其他模块的完全相同,除了缺少注册。

当运行这个时,我得到以下异常:

Exception is: InvalidOperationException - The type DuplexChannelFactory`1 has mu
ltiple constructors of length 3. Unable to disambiguate.

这似乎是一个问题与解析和通道工厂的导演,但为什么可以统一解决工厂在第一个模块,而不是在这个吗?

我也不理解这个异常消息,因为我认为在注册中调用了一个特定的tor:

new InjectionConstructor(
                instanceContext,
                "NetNamedPipeBinding_IGenericTradingInterface")

任何想法?

当在不同的模块中解析时,Unity无法解析类型

您没有显示如何(或是否)在模块之间共享unity容器。根据您的变量名称("unityContainer"),我猜它是模块内的局部变量?这意味着您有两个独立的容器实例,每个实例都需要注册。

原来问题出在模块初始化的顺序。第二个模块首先被调用,所以Unity使用最多参数的CTor,而DuplexChannelFactory最多有3个。谢谢,Juergen