Unity - 如何对同一类型使用多个映射并注入到对象中
我正在使用 Unity 2.0,在下面的代码中我尝试在 Worker 对象中注入特定的工具。
我想使用以下代码。但当然有一个错误“依赖关系解析失败”。我相信我应该能够做这样的事情,但我很难弄清楚。
IUnityContainer container = new UnityContainer();
container.RegisterType<IWorker, Worker>("Worker")
.RegisterType<ITool, ToolA>("ToolA")
.RegisterType<ITool, ToolB>("ToolB")
.RegisterType<ITool, ToolC>("ToolC");
IWorker worker = container.Resolve<Worker>("ToolA");
我知道这行不通,但是我该如何解决这个问题呢?
酒吧开发者
I'm using Unity 2.0 and in the following code I'm trying to inject a specific tool in the Worker object.
I would like to use the following code. But ofcourse there is an error "Resolution of the dependency failed". I believe I should be able to do something like this, but I'm having a difficult time figuring it out.
IUnityContainer container = new UnityContainer();
container.RegisterType<IWorker, Worker>("Worker")
.RegisterType<ITool, ToolA>("ToolA")
.RegisterType<ITool, ToolB>("ToolB")
.RegisterType<ITool, ToolC>("ToolC");
IWorker worker = container.Resolve<Worker>("ToolA");
I know this doesn't work, but how would I resolve this issue?
BarDev
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两种方法可以实现此目的:
您可以使用 ParameterOverride 和两步解析过程......
假设接收的
Worker
上的构造函数参数ITool
称为“工具”(多个ParameterOverride
实例可以传递给Resolve
)。IWorker
的命名实例具有的任何其他依赖项(通过构造函数或属性注入)也应该正确解析。或者,为什么不设置需要指定 ITool 的命名
WorkerA、WorkerB、WorkerC
实例...我认为后一种方法的缺点是,如果
Worker< /code> 需要额外的构造函数参数,您还需要将它们指定给
InjectionConstructor
,指定顺序与您期望 Unity 使用的构造函数相同...但是,Unity 会查找非上例中
SomeDependency
和SomeOtherDependency
的命名实例,这样可以节省您的一些工作。There are two ways you can achieve this:
You can use
ParameterOverride
's and a two step resolution process......assuming that the constructor argument on
Worker
that receives theITool
is called 'tool' (multipleParameterOverride
instances can be passed toResolve
). Any other dependencies (via constructor or property injection) that the named instance ofIWorker
has should be correctly resolved as well.Alternatively, why not setup named
WorkerA, WorkerB, WorkerC
instances that require the specifiedITool
...The disadvantage I suppose with the latter approach is that if
Worker
takes additional constructor parameters you will need to specify them to theInjectionConstructor
as well, specified in the same order as the constructor you are expecting Unity to use...However, Unity will lookup the non-named instance of
SomeDependency
andSomeOtherDependency
in the above example, so that saves you a bit of work.