How to resolve dependency by using a named registertype in Unity?

1.7k Views Asked by At
public interface IFoo {}

public interface IBar {}

public class Foo1 :  IFoo {}

public class FooOne : IFoo {}
public class FooTwo : IFoo {}

public class BarOne : IBar
{
    public BarOne(IFoo foo) {}        
} 

public class BarTwo : IBar
{
    public BarTwo(IFoo foo) {}        
} 

 class Program
{
    static void Main(string[] args)
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<IFoo, FooOne>("One")
            .RegisterType<IFoo, FooTwo>("Two")
            .RegisterType<IBar, BarOne>("One")
            .RegisterType<IFoo, BarTwo>("Two");                

        string fooType = "One";
        string barType = "Two";

        IFoo myFoo = container.Resolve<IFoo>(fooType);
        IBar myBar = container.Resolve<IBar>(barType);
    }
}

Code sample above throws this error :

Resolution of the dependency failed, type = "ConsoleApplication5.IBar", name = "Two". Exception occurred while: while resolving. Exception is: InvalidOperationException - The current type, ConsoleApplication5.IFoo, is an interface and cannot be constructed. Are you missing a type mapping? ----------------------------------------------- At the time of the exception, the container was:

Resolving ConsoleApplication5.BarTwo,Two (mapped from ConsoleApplication5.IBar, Two) Resolving parameter "foo" of constructor ConsoleApplication5.BarTwo(ConsoleApplication5.IFoo foo) Resolving ConsoleApplication5.IFoo,(none)

My solution is using DependencyResolver which changes this line:

IBar myBar = container.Resolve<IBar>(barType);

to this:

IBar myBar = container.Resolve<IBar>(barType, new DependencyOverride<IFoo>(myFoo));

I want to solve this issue using RegisterType method. Is it possible or is there any other solution?

Thanks.

1

There are 1 best solutions below

8
On

You have to determine which of your IFoo named registrations unity should use when your resolving an IBar.

container.RegisterType<IFoo, FooOne>("One")
         .RegisterType<IFoo, FooTwo>("Two")
         .RegisterType<IBar, BarOne>("One", new InjectionConstructor(
                                     new ResolvedParameter<IFoo>("One")))
         .RegisterType<IBar, BarTwo>("Two", new InjectionConstructor(
                                     new ResolvedParameter<IFoo>("Two")));

The Problem is that IFoo is twice registered by different implementations and unity does not know which one it should use when resolving that type.