Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 682
n4cer500 Avatar asked Mar 11 '13 18:03

n4cer500


People also ask

What is the use of Autofac in MVC?

AutoFac provides better integration for the ASP.NET MVC framework and is developed using Google code. AutoFac manages the dependencies of classes so that the application may be easy to change when it is scaled up in size and complexity.

Does Autofac use reflection?

You register components with Autofac by creating a ContainerBuilder and informing the builder which components expose which services. Components can be created via reflection (by registering a specific .

What is Autofac IoC?

Autofac is an IoC container for Microsoft . NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular . NET classes as components.


1 Answers

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);
}
like image 169
nemesv Avatar answered Sep 18 '22 15:09

nemesv