使用 ASP.NET 核心 DI 注册一个 MediatR 流水线约束后处理器

Registering a MediatR pipeline constrained PostProcessor using ASP.NET Core DI

以前,我们有以下管道设置用于审计记录目的

    public class AuditLogPostProcessor<TRequest, TResponse> : 
           IRequestPostProcessor<TRequest, TResponse> 
              where TRequest : IAuditLogRequest<TResponse>

其中 IAuditLogRequest 实现 IRequest

public interface IAuditLogRequest<TResponse> : IRequest<TResponse>

所有且只有实现 IAuditLogRequest 的命令到达了 AuditLogPostProcessor。

使用 SimpleInjector 注册如下

_container.RegisterCollection(typeof(IRequestPostProcessor<,>), 
    new[] { typeof(GenericRequestPostProcessor<,>),typeof(AuditLogPostProcessor<,>) });

目前,我们使用 ASP.NET 核心 DI 进行依赖注入,注册如下。

services.AddScoped(typeof(IRequestPostProcessor<,>), typeof(GenericRequestPostProcessor<,>));
services.AddScoped(typeof(IRequestPostProcessor<,>), typeof(AuditLogPostProcessor<,>));

当命令执行 IRequest 时,我们收到错误

TypeLoadException: GenericArguments[0], 'Command', 
on 'AuditLogPostProcessor`2[TRequest,TResponse]' violates 
the constraint of type parameter 'TRequest'.

看来 DI 没有遵守约束条件。我可以使用 ASP.NET Core DI 获得所需的行为吗?

我们有类似的设置。

如果您的处理程序实现了 IRequestPostProcessor,您需要做的就是将它添加到您的 DI 中:

services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));

我也想做同样的事情。显然 ASP.net 核心 DI 不支持此功能。

SRC:Support constrained open generic types

您需要使用其他容器,例如Autofac 或StructureMap。 示例:Autofac for ASP.NET core

非常简单,不需要太多改动