Autofac:批量注册开放类型

编程入门 行业动态 更新时间:2024-10-24 10:22:51
本文介绍了Autofac:批量注册开放类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我得到了具有许多实现 IHandler< TCommand> 的具体类型的程序集,例如:

I got an assembly with many concrete types that implement IHandler<TCommand>, such as the following:

public class MoveCustomerHandler : IHandler<MoveCustomerCommand> { void IHandler<MoveCustomerCommand>.Handle(MoveCustomerCommand c) { // some business logic for moving a customer. } }

当前,我正在将它们逐个注册为

Currently, I'm registering them one by one as follows:

builder.RegisterType<MoveCustomerHandler>() .As<IHandler<MoveCustomerCommand>>(); builder.RegisterType<ProcessOrderHandler>() .As<IHandler<ProcessOrderCommand>>(); builder.RegisterType<SomeOtherFancyHandler>() .As<IHandler<SomeOtherFancyCommand>>(); // Many handler registrations here...

命令处理程序是使用构造函数注入来注入,如下所示:

The command handlers are injected using constructor injection, as can be seen below:

public class OrderController { private readonly IHandler<ProcessOrderCommand> handler; public OrderController(IHandler<ProcessOrderCommand> handler) { this.handler = handler; } }

是否可以批量注册我的所有处理程序

Is there a way to batch register all my handlers in an easy way using Autofac?

推荐答案

与Jim的答案类似,但要利用 AsClosedTypesOf :

In a similar style to Jim's answer but taking advantage of AsClosedTypesOf:

Assembly[] assemblies = GetYourAssemblies(); builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof(IHandler<>));

更多推荐

Autofac:批量注册开放类型

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

发布评论

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

>www.elefans.com

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