将含有所有已注册的实现接口的可枚举 [英] Injecting an Enumerable containing all registered Implementations of an Interface
问题描述
由于以下接口:
公共接口IMyProcessor
{
无效处理();
}
我想可以注册多个实现,并有我的DI容器注入他们的枚举到这样一个类:
公共类MyProcessorLibrary
{
私人只读IMyProcessor [] _processors;
公共MyProcessingThing(IMyProcessor []处理器)
{
this._processors =处理器;
}
公共无效ProcessAll()
{
的foreach(在this._processors VAR处理器)
{
processor.Process() ;
}
}
}
这可能吗?我目前的实施 MyProcessorLibrary
查找所有的 IMyProcessor
实现静态,但我宁愿做,如果通过一个容器我可以。我使用Unity,但很好奇,如果其他容器支持。
编辑:
感谢迄今答案;要清楚我要注入 MyProcessorLibrary
到另一个类,并将其建成了依赖对象的树,如:
公共类MyProcessorRepository
{
公共MyProcessorRepository(MyProcessorLibrary processorLibrary)
{
}
}
公共类MyProcessorService
{
公共MyProcessorService(MyProcessorRepository processorRepository)
{
}
}
变种集装箱=新UnityContainer();
//注册一堆IMyProcessors的...
VAR的服务= container.Resolve< MyProcessorService>();
我不能统一发言,因为我不T选用它,但它肯定是可能的 Ninject (见的多次注射),我确实使用。
Given the following interface:
public interface IMyProcessor
{
void Process();
}
I'd like to be able to register multiple implementations and have my DI container inject an enumerable of them into a class like this:
public class MyProcessorLibrary
{
private readonly IMyProcessor[] _processors;
public MyProcessingThing(IMyProcessor[] processors)
{
this._processors = processors;
}
public void ProcessAll()
{
foreach (var processor in this._processors)
{
processor.Process();
}
}
}
Is this possible? My current implementation of MyProcessorLibrary
looks up all the IMyProcessor
implementations statically, but I'd rather do it through a container if I can. I'm using Unity, but am curious if other containers support it.
Edit:
Thanks for the answers so far; to be clear I want to inject MyProcessorLibrary
into another class, and have it built as part of the wiring up of a tree of dependent objects, e.g.
public class MyProcessorRepository
{
public MyProcessorRepository(MyProcessorLibrary processorLibrary)
{
}
}
public class MyProcessorService
{
public MyProcessorService(MyProcessorRepository processorRepository)
{
}
}
var container = new UnityContainer();
// Register a bunch of IMyProcessors...
var service = container.Resolve<MyProcessorService>();
I can't speak for Unity as I don't use it but it is definitely possible with Ninject (see Multi Injection) which I do use.
这篇关于将含有所有已注册的实现接口的可枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!