18

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?

n4cer500
  • 743
  • 1
  • 8
  • 21

1 Answers1

29

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);
}
Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • nemesv I have a very similar question - don't suppose you could help? https://stackoverflow.com/questions/64363768/include-list-of-resolved-dependancies-of-irepository-with-autofac – Jono Oct 15 '20 at 01:51