向Autofac注册基类的实现以通过IEnumerable传递 [英] Registering implementations of base class with Autofac to pass in via IEnumerable
问题描述
我有一个基类,还有一系列其他继承自此的类:
(请原谅过度使用的动物类比)
公共抽象类动物{}
公共课狗:动物{}
公共课程Cat:动物{}
然后我有了一个依赖于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
传递给构造函数.
我错过了什么吗?
您在注册中缺少As<Animal>()
呼叫.
没有它,Autofac将使用默认的AsSelf()
设置注册您的类型,因此,仅当您使用诸如Dog和Cat之类的子类型时,如果您请求使用IEnumerable<Animal>
的基本类型,就不会得到您的类.>
因此将您的注册更改为:
builder.RegisterAssemblyTypes(typeof(Animal).Assembly)
.Where(t => t.IsSubclassOf(typeof(Animal)))
.As<Animal>();
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?
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>();
这篇关于向Autofac注册基类的实现以通过IEnumerable传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!