Autofac:开放泛型类型的批量注册

时间:2011-04-26 11:53:54

标签: c# .net 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.
    }
}

目前,我正按照以下方式逐一注册:

builder.RegisterType<MoveCustomerHandler>()
    .As<IHandler<MoveCustomerCommand>>();

builder.RegisterType<ProcessOrderHandler>()
    .As<IHandler<ProcessOrderCommand>>();

builder.RegisterType<SomeOtherFancyHandler>()
    .As<IHandler<SomeOtherFancyCommand>>();

// Many handler registrations here...

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

public class OrderController
{
    private readonly IHandler<ProcessOrderCommand> handler;

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

有没有办法使用Autofac以简单的方式批量注册我的所有处理程序?

2 个答案:

答案 0 :(得分:26)

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

Assembly[] assemblies = GetYourAssemblies();

builder.RegisterAssemblyTypes(assemblies)
    .AsClosedTypesOf(typeof(IHandler<>));

答案 1 :(得分:3)

你可能想要这样的东西,虽然我不确定IsAssignable()如何用开放的泛型来表现。

Assembly[] assemblies = GetYourAssemblies();

builder.RegisterAssemblyTypes(assemblies)
    .Where(t => t.IsAssignableFrom(typeof(IHandler<>)))
    .AsSelf()
    .AsImplementedInterfaces();