Registering implementations of base class with Autofac to pass in via IEnumerable

放肆的年华 提交于 2020-01-02 01:10:19

问题


I have a base class, and a series of other classes inheriting from this:
(Please excuse the over-used animal analogy)

public abstract class Animal { }

public class Dog : Animal { }

public class Cat : Animal { }

I then have a class that has a dependancy on an 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 can see that this returns Dog and Cat

However, when I try to wire up my Autofac like this:

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

builder.RegisterType<AnimalFeeder>();

When AnimalFeeder is instantiated, there are no Animal passed in to the constructor.

Have I missed something?


回答1:


You are missing the As<Animal>() call in your registration.

Without it Autofac will register your types with the default AsSelf() setting so you won't get your classes if you ask for base type with IEnumerable<Animal> only if you use the sub-types like Dog and Cat.

So change your registration to:

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


来源:https://stackoverflow.com/questions/20372993/registering-implementations-of-base-class-with-autofac-to-pass-in-via-ienumerabl

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