是否可以使用Autofac将已解析对象的列表注入到构造函数中? [英] Is it possible to inject a list of resolved objects into a constructor using Autofac?

查看:178
本文介绍了是否可以使用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 supplies IEnumerable<ITask>. Instead, the container will find all implementations of ITask and inject all of them.

因此将您的构造函数更改为:

So change your constructor to:

public Detector(IEnumerable<IRecognizer> recognizers)
{
    this.Recognizers = new List<IRecognizer>(recognizers);
}

这篇关于是否可以使用Autofac将已解析对象的列表注入到构造函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆