Search code examples
c#unity-container

Unity Container same type name but from different Namespaces


I have to build a unity container to inject dependencies in my asp.net project. In that project, I have to register two types which are from different namespaces but have the same name. So how can I register both types into one unity container?

container.RegisterType<IType, Type>()
container.RegisterType<IType, Type>();

Here ITypes and Types are from a different namespace. But have the same names. So how can I register both in one container? I'm using Unity Container version 5.2.0.0


Solution

  • I've not used Unity, but assuming it's the same as any other container, it should be as simple as this:

    container.RegisterType<NamespaceA.IType, NamespaceA.Type>()
    container.RegisterType<NamespaceB.IType, NamespaceB.Type>();
    

    Essentially, types will be registered internally using their Type metadata, so the container will see them as two completely separate types, just as if they were called ITypeA and ITypeB.

    Then when you inject them, you just have to make sure you're referencing the correct namespace.

    If you need both of them, explicitly reference both namespaces:

    public MyService(NamespaceA.IType aType, NamespaceB.IType bType)
    

    Or, if you only need one, then simply reference the namespace with a using (or explicitly) and inject it as normal:

    using NamespaceA;
    
    public class MyService
    {
        public MyService(IType aType)
        {
        }
    }