如何在 Autofac 中注册许多开放通用 [英] How to register many for open generic in Autofac
问题描述
我是 Autofac 的新手(不是 DI).情况如下:
I'm new to Autofac (not to DI). Here is the situation:
我有这些接口:
public interface IQuery<out TResult> : IQuery { }
public interface IQueryHandler<in TQuery, out TResult> where TQuery : IQuery<TResult> {
TResult Handle(TQuery query);
}
并且在我的解决方案中有很多实现:
and there is a lot of implementation of them in my solution:
class GetPersonQuery : IQuery<PersonModel> { }
class GetPersonQueryHandler : IQueryHandler<GetPersonQuery, PersonModel> { }
class GetArticleQuery : IQuery<ArticleModel> { }
class GetArticleQueryHandler : IQueryHandler<GetArticleQuery, ArticleModel> { }
class GetSomethingQuery : IQuery<IEnumerable<SomeModel>> { }
class GetSomethingQueryHandler : IQueryHandler<GetSomethingQuery, IEnumerable<SomeModel>> { }
等等.我目前正在像这样注册它们:
and so on. I'm currently registering them like this:
builder.RegisterType<GetPersonQueryHandler>()
.As<IQueryHandler<GetPersonQuery, PersonModel>>();
builder.RegisterType<GetArticleQueryHandler>()
.As<IQueryHandler<GetArticleQuery, ArticleModel>>();
builder.RegisterType<GetSomethingQueryHandler>()
.As<IQueryHandler<GetSomethingQuery, SomeModel>>();
// blah blah blah
如您所见,我有许多相同的注册.在 SimpleInjector
(我之前使用过)中,我可以通过一行来注册所有这些:
As you can see, I have a many same registrations. In SimpleInjector
(which I was using before), I could register all of them by a single line:
container.RegisterManyForOpenGeneric(
typeof(IQueryHandler<,>),
AppDomain.CurrentDomain.GetAssemblies());
是否可以在 Autofac 中执行此操作?
Is it possible to do this stuff in Autofac?
推荐答案
您可以使用 Autofac 做到这一点,您只需要使用 扫描功能并使用AsClosedTypesOf
方法:
You can do this with Autofac you just need to use the scanning feature and use the AsClosedTypesOf
method:
AsClosedTypesOf(open)
- 注册可分配给开放泛型类型的封闭实例的类型.
AsClosedTypesOf(open)
- register types that are assignable to a closed instance of the open generic type.
所以您的注册将如下所示:
So your registration will look like this:
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.AsClosedTypesOf(typeof (IQueryHandler<,>)).AsImplementedInterfaces();
这篇关于如何在 Autofac 中注册许多开放通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!