如何在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?
推荐答案
您只需使用扫描功能并使用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屋!