Ste*_*ven 14 .net c# dependency-injection ioc-container autofac
我得到了一个具有许多具体类型的程序集,IHandler<TCommand>如下所示:
public class MoveCustomerHandler : IHandler<MoveCustomerCommand>
{
void IHandler<MoveCustomerCommand>.Handle(MoveCustomerCommand c)
{
// some business logic for moving a customer.
}
}
Run Code Online (Sandbox Code Playgroud)
目前,我正按照以下方式逐一注册:
builder.RegisterType<MoveCustomerHandler>()
.As<IHandler<MoveCustomerCommand>>();
builder.RegisterType<ProcessOrderHandler>()
.As<IHandler<ProcessOrderCommand>>();
builder.RegisterType<SomeOtherFancyHandler>()
.As<IHandler<SomeOtherFancyCommand>>();
// Many handler registrations here...
Run Code Online (Sandbox Code Playgroud)
使用构造函数注入注入命令处理程序,如下所示:
public class OrderController
{
private readonly IHandler<ProcessOrderCommand> handler;
public OrderController(IHandler<ProcessOrderCommand> handler)
{
this.handler = handler;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用Autofac以简单的方式批量注册我的所有处理程序?
Nic*_*rdt 26
与Jim的答案类似,但利用AsClosedTypesOf:
Assembly[] assemblies = GetYourAssemblies();
builder.RegisterAssemblyTypes(assemblies)
.AsClosedTypesOf(typeof(IHandler<>));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4265 次 |
| 最近记录: |