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