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

烈酒焚心 提交于 2019-12-13 12:10:27

问题


I'm trying to register the same type but with two different constructors. When I trying to resolve, I get "Resolution of the dependency failed" on the second Resolve.

    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 I'm doing wrong?


回答1:


You need to give them names when registering. The parameter to Resolve is the name of the instance you want.

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


来源:https://stackoverflow.com/questions/870470/how-to-register-same-type-twice-with-different-constructors-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!