使用ASP.NET Core DI注册MediaTR管道约束后处理器



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

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

其中iauditlogrequest实现了iirequest

public interface IAuditLogRequest<TResponse> : IRequest<TResponse>

所有实现IauditLogrequest的命令到达了AuditLogPostProcessor。

使用简单注射器的注册如下

_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?

获得所需的行为

我想做的是完全相同的事情。显然ASP.NET Core DI不支持此功能。

src:支持受约束的开放式通用类型

您需要使用另一个容器,例如AutoFac或structuremap。示例:asp.net core

的autoFac

这很简单,并且不需要太多更改

我们有类似的设置。

如果您的处理程序实现了IreQuestPostProcessor,那么您需要做的就是将其添加到您的di:

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

最新更新