如何使用Microsoft Unity IOC容器注入IEnumerable [英] How to inject IEnumerable using Microsoft Unity IOC container
本文介绍了如何使用Microsoft Unity IOC容器注入IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一项服务,需要注入多个提供者,例如,请参见下文.如何使用Unity来实现此功能?
I have a Service that need inject more than one provider, see below for example. How to use Unity to implement this feature?
public class MyService: IMyService
{
public MyService(IEnumerable<Provider> Providers);
}
推荐答案
我知道这是一个老问题,但这也许会帮助其他偶然发现此问题的人.
I know this is an old question, but maybe this will help someone else that stumbles upon this.
只要使用特定名称注册实现,就可以轻松注入.然后,您将获得所有注册的实现.
As long as you register the implementations with a specific name, this is possible to easily inject. You will then get all registered implementations.
public class MyService: IMyService
{
public MyService(IProvider[] providers)
{
// Do something with the providers
}
}
只需确保将它们作为数组注入即可. Unity将理解这一点.当您注册它们时,您可以这样注册它们:
Just make sure to inject them as an array. Unity will understand this. And when you register them you can register them as such:
container.RegisterType<IProvider, FooProvider>("Foo");
container.RegisterType<IProvider, BarProvider>("Bar");
这篇关于如何使用Microsoft Unity IOC容器注入IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文