MediatR IPipelineBehavior<TRequest, TResponse> 错误,因为类型 'TRequest' 不能用作泛型类型或方法中的类型参数 'TRequest'

MediatR IPipelineBehavior<TRequest, TResponse> errors as The type 'TRequest' cannot be used as type parameter 'TRequest' in the generic type or method

我正在使用 MediatR 在我的应用程序中使用 IPipelineBehavior<TRequest, TResponse>

执行请求 - 响应日志记录

代码示例:

internal sealed class AppLoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
    private readonly ILogger<AppLoggingBehavior<TRequest, TResponse>> _logger;

    public AppLoggingBehavior(ILogger<AppLoggingBehavior<TRequest, TResponse>> logger)
    {
        _logger = logger;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        string requestName = typeof(TRequest).Name;
        string unqiueId = Guid.NewGuid().ToString();
        string requestJson = JsonSerializer.Serialize(request);
        _logger.LogInformation($"Begin Request Id:{unqiueId}, request name:{requestName}, request json:{requestJson}");
        var timer = new Stopwatch();
        timer.Start();
        var response = await next();
        timer.Stop();
        _logger.LogInformation($"End Request Id:{unqiueId}, request name:{requestName}, total request time:{timer.ElapsedMilliseconds}ms");
        return response;
    }
}

但是在升级到 Nuget - v10.0.0 之后,我开始遇到以下编译错误。

The type 'TRequest' cannot be used as type parameter 'TRequest' in the generic type or method 'IPipelineBehavior<TRequest, TResponse>'. There is no boxing conversion or type parameter conversion from 'TRequest' to 'MediatR.IRequest'

我设法从官方 MediatR 存储库中找到了 porting guide。但是找不到任何例子。

我还遗漏了什么吗,请问有人能帮我解决这个问题吗?

您还需要在摘要 class 中指定 TRequest 参数的类型。它必须至少是特定于您要实现的接口中的参数。

internal sealed class AppLoggingBehavior<TRequest, TResponse>
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : MediatR.IRequest<TResponse> // <- this is the part you're missing
{
    // rest of your code...
}