使用ASP.NET Core DI注册MediatR管道限制后处理器

3
以前,我们已经建立了以下管道来实现审计日志记录目的。
    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 Core 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 中获得所需的行为?

2个回答

3

1
我们有类似的设置。
如果您的处理程序实现了IRequestPostProcessor,您只需要将以下内容添加到DI中即可:
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接