Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Autofac:开放泛型类型的批量注册_C#_.net_Dependency Injection_Ioc Container_Autofac - Fatal编程技术网

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

C# Autofac:开放泛型类型的批量注册,c#,.net,dependency-injection,ioc-container,autofac,C#,.net,Dependency Injection,Ioc Container,Autofac,我得到了一个包含许多具体类型的程序集,这些类型实现了IHandler,例如: public class MoveCustomerHandler : IHandler<MoveCustomerCommand> { void IHandler<MoveCustomerCommand>.Handle(MoveCustomerCommand c) { // some business logic for moving a customer.

我得到了一个包含许多具体类型的程序集,这些类型实现了
IHandler
,例如:

public class MoveCustomerHandler : IHandler<MoveCustomerCommand>
{
    void IHandler<MoveCustomerCommand>.Handle(MoveCustomerCommand c)
    {
        // some business logic for moving a customer.
    }
}
公共类移动CustomerHandler:IHandler
{
void IHandler.Handle(移动客户命令c)
{
//移动客户的一些业务逻辑。
}
}
目前,我正在逐一注册,如下所示:

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

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

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

// Many handler registrations here...
builder.RegisterType()
.As();
builder.RegisterType()
.As();
builder.RegisterType()
.As();
//这里有很多处理程序注册。。。
命令处理程序使用构造函数注入进行注入,如下所示:

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

    public OrderController(IHandler<ProcessOrderCommand> handler)
    {
        this.handler = handler;
    }
}
公共类OrderController
{
私有只读IHandler处理程序;
公共订单管理员(IHandler处理程序)
{
this.handler=handler;
}
}

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

您可能想要这样的方式,尽管我不确定IsAssignable()在开放泛型中的行为

Assembly[] assemblies = GetYourAssemblies();

builder.RegisterAssemblyTypes(assemblies)
    .Where(t => t.IsAssignableFrom(typeof(IHandler<>)))
    .AsSelf()
    .AsImplementedInterfaces();
Assembly[]assemblies=GetYourAssembly();
builder.RegisterAssemblyTypes(程序集)
其中(t=>t.IsAssignableFrom(typeof(IHandler)))
.AsSelf()
.a实现接口();

与Jim的回答风格相似,但利用了
的封闭类型

Assembly[] assemblies = GetYourAssemblies();

builder.RegisterAssemblyTypes(assemblies)
    .AsClosedTypesOf(typeof(IHandler<>));
Assembly[]assemblies=GetYourAssembly();
builder.RegisterAssemblyTypes(程序集)
.AsClosedTypesOf(typeof(IHandler));

感谢您的回复。我不知道你想在这里完成什么。
Type.GetCustomAttributes()
方法返回一个
对象[]
,这对我有什么帮助?我的错。我试图在浏览器文本框中复制/粘贴和编辑。我删掉了那部分。