How to register the same type twice with different constructors in Unity?

I am trying to register the same type, but with two different constructors. When I try to resolve, I get "Dependency Resolution Failed" in the second resolution.

    var container = new UnityContainer();

    container.RegisterType<IBar, Bar>()
        .RegisterInstance(new Bar())
        .RegisterType<IBar, Bar>()
        .RegisterInstance(new Bar("foo"));

    Bar bar1 = (Bar)container.Resolve<IBar>();
    Bar bar2 = (Bar)container.Resolve<IBar>("foo");  // ERROR

What am I doing wrong?

+3
source share
1 answer

You need to provide names during registration. The parameter Resolveis the name of the required instance.

var container = new UnityContainer();

container
    .RegisterInstance<IBar>("BAR", new Bar())
    .RegisterInstance<IBar>("FOOBAR", new Bar("foo"));

Bar bar1 = (Bar)container.Resolve<IBar>("BAR");
Bar bar2 = (Bar)container.Resolve<IBar>("FOOBAR");
+6
source

Source: https://habr.com/ru/post/1708451/


All Articles