使用Autofac注册基类的实现,以通过IEnumerable传入

时间:2013-12-04 10:36:39

标签: c# dependency-injection inversion-of-control autofac

我有一个基类,还有一系列继承自此类的其他类:
(请原谅过度使用的动物类比)

  

公共抽象类Animal {}

     

公共课Dog:Animal {}

     

公共类Cat:Animal {}

然后我有一个依赖于IEnumerable<Animal>

的班级
public class AnimalFeeder
{
    private readonly IEnumerable<Animal> _animals;

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

如果我手动做这样的事情:

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

然后我可以看到这会返回DogCat

然而,当我尝试连接我的Autofac时:

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

builder.RegisterType<AnimalFeeder>();

实例化AnimalFeeder时,没有Animal传入构造函数。

我错过了什么吗?

1 个答案:

答案 0 :(得分:16)

您在注册时错过了As<Animal>()来电。

没有它Autofac会使用默认的AsSelf()设置注册您的类型,因此如果您使用IEnumerable<Animal>的基本类型,只有在使用像Dog这样的子类型时才会获得您的类猫。

所以请将注册更改为:

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