注册同一份合约的多种实现:一种在Chilcontainer中,另一种在父级中 [英] Register Multiple implementations of the same contract : one in Chilcontainer and one in the Parent

查看:138
本文介绍了注册同一份合约的多种实现:一种在Chilcontainer中,另一种在父级中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试注册相同接口的多个实现,例如:-

I am trying to register multiple implementations of the same interface like this :-

**DLL A: Module.cs**
_container.RegisterType<IFoo, Foo1>("Foo1");


**DLL B: Module.cs**
var childContainer = _container.CreateChildContainer(); //childcontainer
childContainer.RegisterType<IFoo, Foo2>("Foo2");


**DLL A: Resolve IFoo for Foo2** (But, resolving IFoo for Foo1 is fine)
var foo2 = container.Resolve<IFoo>("Foo2"); //Error

注意:我在这里收到的容器是"childcontainer". 检查了哈希码.

Note: The container which I receive here is the "childcontainer". Have checked the hashcode.

错误:

第一次机会例外 类型"System.InvalidOperationException"的发生在 Microsoft.Practices.Unity.dll

A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.Practices.Unity.dll

其他信息:当前类型IFoo是接口, 无法建造.您是否缺少类型映射?

Additional information: The current type, IFoo, is an interface and cannot be constructed. Are you missing a type mapping?


但是,如果我在Foo1之后立即在DLL A中进行Foo2的注册,即这样:


But, it works, if I do the registration of Foo2 in DLL A just after Foo1 i.e. like this :

_container.RegisterType<IFoo, Foo1>("Foo1");
_container.RegisterType<IFoo, Foo2>("Foo2");

Registration (Register) and Resolution (Resolve)是否取决于范围&部件 ?我希望第一种方法起作用.有什么主意吗?

Is Registration (Register) and Resolution (Resolve) dependent upon scope & assembly ? I want the 1st approach to work. Any idea ?

推荐答案

我尝试了下一个示例,现在正在为我工​​作.只是要小心程序集引用和名称空间包括.

I tried the next example and is working for me. Just be carefull with assembly references and namespace includes.

**Dll A

Public  Interface Ifoo

 End Interface


**Dll B


 Public Class Class1

        Public Shared function registerOtherType(container AS IUnityContainer) As IUnityContainer
            Dim c As IUnityContainer = container.CreateChildContainer
            c.RegisterType(of Ifoo, foo2)("2")
            Return c
     End Function


    End Class

    Public Class foo2
        Implements Ifoo

    End Class


**Dll C

    Public Class foo
        Implements Ifoo

 End Class

    Sub Main()
        'init()
        'Dim manager As IClasificationManagement = ServiceLocator.Current.GetInstance(Of IClasificationManagement)()
        'manager.SwapDescrition("1", "2")
        'Console.WriteLine("Operacion Realizada")
        'Console.Read()
        Dim container As IUnityContainer = New UnityContainer()
        container.RegisterType(Of Ifoo, foo )("1")
        dim child As IUnityContainer = Class1.registerOtherType(container)
        child.Resolve(of Ifoo)("2")

    End Sub

这篇关于注册同一份合约的多种实现:一种在Chilcontainer中,另一种在父级中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆