本文介绍了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:批量注册开放类型
发布评论