如何在Unity中向不同的构造函数两次注册同一类型? [英] How to register same type twice with different constructors in Unity?
本文介绍了如何在Unity中向不同的构造函数两次注册同一类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试注册相同的类型,但使用两个不同的构造函数.当我尝试解析时,在第二个解析中得到"依赖项解析失败".
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
我做错了什么?
推荐答案
注册时需要给他们起名字. Resolve
的参数是所需实例的名称.
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");
这篇关于如何在Unity中向不同的构造函数两次注册同一类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文