如何在Autofac中为开放式通用注册许多

编程入门 行业动态 更新时间:2024-10-25 23:28:15
本文介绍了如何在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中为开放式通用注册许多

本文发布于:2023-11-04 12:25:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:开放式   中为   如何在   Autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!