让 Autofac 返回通用抽象而不是具体类
我正在尝试使用 Autofac 自动装配我的应用程序。一切都很好,除了我有一个抽象泛型类型,例如:
public abstract class Transformer<TModel>
{
// Some abstract methods
}
它实现为:
public class EventTransformer : Transformer<Event>
{
// implementation of methods
}
我自动装配应用程序:
builder.RegisterAssemblyTypes(typeof (MyAssemblyName).Assembly)
.InstancePerLifetimeScope();
Autofac 在解析这种类型的类时会抛出一个错误:
public class RandomClass<TModel>
{
public RandomClass(Transformer<TModel> transformer()
{
// Constructor code
}
}
我得到下面的错误(简化的) )。我可以手动将 EventTransformer 注册为 Transformer <活动>一切工作正常,但我不想手动注册它,我应该能够自动注册,这样我就可以简单地创建一个新类,然后将其直接添加到应用程序中。
The requested service Transformer`1[[Event]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
我确实在注册类时尝试使用方法 .AsImplementedInterfaces() 但它似乎不起作用。
那么我应该做什么来实现这个目标呢?另外,对于奖励积分,我无法知道 Autofac 正在注册什么以及将其注册为什么。有办法这样做吗?
I'm trying to autowire up my application using Autofac. All is fine apart from the fact I have an abstract generic type such as:
public abstract class Transformer<TModel>
{
// Some abstract methods
}
With it implemented as:
public class EventTransformer : Transformer<Event>
{
// implementation of methods
}
I'm autowiring up the application with:
builder.RegisterAssemblyTypes(typeof (MyAssemblyName).Assembly)
.InstancePerLifetimeScope();
Autofac will then throw an error when resolving this type of class:
public class RandomClass<TModel>
{
public RandomClass(Transformer<TModel> transformer()
{
// Constructor code
}
}
I get the error below (simplified). I can register the EventTransformer manually as Transformer < Event > and everything works fine, but I don't want to have to register it manually, I should be able to do it automatically so I can simply create a new class and it's straight into the application.
The requested service Transformer`1[[Event]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
I did try and use the method .AsImplementedInterfaces() when registering the classes but it didn't seem to work.
So what should I be doing to accomplish this? Also for bonus points, I have no way of knowing what Autofac is registering and what it's registering it as. Is there anyway of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用
AsClosedTypesOf
开放泛型类型 > 程序集扫描期间的方法:您可以通过以下方式获取已注册的组件:
You need to register the open generic types with the
AsClosedTypesOf
method during assembly scanning:And you can get the registered components with: