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

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

公共抽象类Animal {}

公共课狗:动物{}

公共类猫:动物{}

然后我有一个依赖于IEnumerable

 public class AnimalFeeder { private readonly IEnumerable _animals; public AnimalFeeder(IEnumerable 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 ,没有Animal传入构造函数。

我错过了什么吗?

您在注册时缺少As()调用。

如果没有它,Autofac将使用默认的AsSelf()设置注册您的类型,这样,如果您使用IEnumerable基本类型,只有在使用Dog和Cat等子类型时才会获得类。

所以将注册更改为:

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