是否可以使用Autofac将已解析对象的列表注入到构造函数中? [英] Is it possible to inject a list of resolved objects into a constructor using Autofac?
问题描述
我是Autofac(3)的新手,并且正在使用它在实现IRecognizer的多个程序集中查找许多类.
I'm new to Autofac (3) and am using it to find a number of classes in several assemblies that implement IRecognizer.
所以我有
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).As<IRecognizer>();
很好.
但我想将对找到的组件的引用注入到构造函数中-
But I'd like to inject references to the found components into a constructor - sort of:
public Detector(List<IRecognizer> recognizers)
{
this.Recognizers = recognizers;
}
有没有办法做到这一点?
Is there any way to do this?
推荐答案
Autofac支持IEnumerable<T>
作为关系类型:
Autofac supports the IEnumerable<T>
as a relationship type:
例如,当Autofac注入类型为的构造函数参数时
IEnumerable<ITask>
它不会寻找提供IEnumerable<ITask>
.相反,容器会找到所有ITask
的实现并将它们全部注入.
For example, when Autofac is injecting a constructor parameter of type
IEnumerable<ITask>
it will not look for a component that suppliesIEnumerable<ITask>
. Instead, the container will find all implementations ofITask
and inject all of them.
因此将您的构造函数更改为:
So change your constructor to:
public Detector(IEnumerable<IRecognizer> recognizers)
{
this.Recognizers = new List<IRecognizer>(recognizers);
}
这篇关于是否可以使用Autofac将已解析对象的列表注入到构造函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!