Is it possible to inject a list of resolved objects into a constructor using Autofac?

余生颓废 提交于 2019-12-22 01:39:58

问题


I'm new to Autofac (3) and am using it to find a number of classes in several assemblies that implement IRecognizer.

So I have:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).As<IRecognizer>();

which is fine.

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?


回答1:


Autofac supports the IEnumerable<T> as a relationship type:

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);
}


来源:https://stackoverflow.com/questions/15346415/is-it-possible-to-inject-a-list-of-resolved-objects-into-a-constructor-using-aut

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!