C# 向Autofac注册基类的实现以通过IEnumerable传入
我有一个基类和一系列继承自此的其他类:C# 向Autofac注册基类的实现以通过IEnumerable传入,c#,dependency-injection,inversion-of-control,autofac,C#,Dependency Injection,Inversion Of Control,Autofac,我有一个基类和一系列继承自此的其他类: (请原谅过度使用的动物类比) 公共抽象类动物{} 公营狗:动物{} 公共类猫:动物{} 然后我有一个依赖于IEnumerable 然后我可以看到它返回Dog和Cat 但是,当我尝试像这样连接Autofac时: var animals = typeof(Animal).Assembly.GetTypes() .Where(x => x.IsSubclassOf(typeof(Animal))) .ToList()
(请原谅过度使用的动物类比) 公共抽象类动物{} 公营狗:动物{} 公共类猫:动物{} 然后我有一个依赖于
IEnumerable
然后我可以看到它返回Dog
和Cat
但是,当我尝试像这样连接Autofac时:
var animals =
typeof(Animal).Assembly.GetTypes()
.Where(x => x.IsSubclassOf(typeof(Animal)))
.ToList();
builder.RegisterAssemblyTypes(typeof(Animal).Assembly)
.Where(t => t.IsSubclassOf(typeof(Animal)));
builder.RegisterType<AnimalFeeder>();
builder.registerasemblytypes(typeof(Animal.Assembly)
其中(t=>t.IsSubclassOf(typeof(动物));
RegisterType();
当实例化AnimalFeeder
时,没有Animal
传递给构造函数
我错过什么了吗?您错过了注册中的
As()
呼叫
如果没有它,Autofac将使用默认的AsSelf()
设置注册您的类型,因此,如果您使用IEnumerable
请求基类型,则您将无法获得类,仅当您使用子类型如Dog和Cat时
因此,请将您的注册更改为:
builder.RegisterAssemblyTypes(typeof(Animal).Assembly)
.Where(t => t.IsSubclassOf(typeof(Animal)))
.As<Animal>();
builder.registerasemblytypes(typeof(Animal.Assembly)
其中(t=>t.IsSubclassOf(typeof(动物)))
.As();
您可能缺少注册表项中的As()
:builder.RegisterAssemblyTypes(typeof(Animal.Assembly)。其中(t=>t.IsSubclassOf(typeof(Animal))).As()代码>可能要将该注释转换为答案!;-)谢谢,就像我有一个驾车向下投票者一样……我知道这个问题很老了,但是如果你想注册抽象类的一个命名子类呢?命名注册也可以通过IEnumarable
解决,当它们注册类型和名称时。所以builder.RegisterType().As().Named(“Dog”);builder.RegisterType().As().Named(“Cat”)
在本例中,IEnumerable
将同时返回这两个值,但您也可以使用:container.ResolveNamed(“Dog”)代码>。您甚至可以将其与程序集扫描结合起来:builder.registerasemblytypes(…).As()
然后另外注册您的命名对象:builder.RegisterType().named(“Dog”)代码>
builder.RegisterAssemblyTypes(typeof(Animal).Assembly)
.Where(t => t.IsSubclassOf(typeof(Animal)))
.As<Animal>();