Registering an implementation of a base class with Autofac to go through IEnumerable

I have a base class and a number of other classes inheriting from this:
(Please excuse the analogue of the used animal)

public abstract class Animal {}

public class Dog: Animal {}

open class Cat: Animal {}

Then I have a class that has a dependency on IEnumerable<Animal>

 public class AnimalFeeder { private readonly IEnumerable<Animal> _animals; public AnimalFeeder(IEnumerable<Animal> animals ) { _animals = animals; } } 

If I manually do something like this:

 var animals = typeof(Animal).Assembly.GetTypes() .Where(x => x.IsSubclassOf(typeof(Animal))) .ToList(); 

Then I see that this returns Dog and Cat

However, when I try to connect my Autofac, for example:

 builder.RegisterAssemblyTypes(typeof(Animal).Assembly) .Where(t => t.IsSubclassOf(typeof(Animal))); builder.RegisterType<AnimalFeeder>(); 

When AnimalFeeder is created, Animal is not passed in the constructor.

Did I miss something?

+6
source share
1 answer

Your registration is missing an As<Animal>() call.

Without it, Autofac will register your default types AsSelf() , so you will not get your classes if you request the base type with IEnumerable<Animal> only if you use subtypes like Dog and Cat.

So, change your registration to:

 builder.RegisterAssemblyTypes(typeof(Animal).Assembly) .Where(t => t.IsSubclassOf(typeof(Animal))) .As<Animal>(); 
+13
source

Source: https://habr.com/ru/post/959314/


All Articles