3

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

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

IAudiLogRequest 在哪里实现 IRequest

public interface IAuditLogRequest<TResponse> : IRequest<TResponse>

所有且只有实现 IAudiLogRequest 的命令到达 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 获得所需的行为吗?

4

2 回答 2

3

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

SRC:支持受限的开放泛型类型

您需要使用另一个容器,例如 Autofac 或 StructureMap。示例:用于 ASP.NET 核心的 Autofac

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

于 2017-07-20T02:16:05.707 回答
1

我们有类似的设置。

如果您的处理程序实现了 IRequestPostProcessor,您只需将其添加到您的 DI 中:

services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));
于 2017-06-27T16:30:01.313 回答