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

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

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

发布评论

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

>www.elefans.com

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