Register Multiple implementations of the same cont

2019-08-29 08:24发布

问题:

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

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

Error:

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

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


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");

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

回答1:

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