我有一个基类,还有一系列继承自此类的其他类:
(请原谅过度使用的动物类比)
公共抽象类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();
然后我可以看到这会返回Dog
和Cat
然而,当我尝试连接我的Autofac时:
builder.RegisterAssemblyTypes(typeof(Animal).Assembly)
.Where(t => t.IsSubclassOf(typeof(Animal)));
builder.RegisterType<AnimalFeeder>();
实例化AnimalFeeder
时,没有Animal
传入构造函数。
我错过了什么吗?
答案 0 :(得分:16)
您在注册时错过了As<Animal>()
来电。
没有它Autofac会使用默认的AsSelf()
设置注册您的类型,因此如果您使用IEnumerable<Animal>
的基本类型,只有在使用像Dog这样的子类型时才会获得您的类猫。
所以请将注册更改为:
builder.RegisterAssemblyTypes(typeof(Animal).Assembly)
.Where(t => t.IsSubclassOf(typeof(Animal)))
.As<Animal>();