我是 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中为开放式通用注册许多
发布评论