首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MediatR IPipelineBehavior<TRequest,类型'TRequest‘的TResponse>错误不能用作泛型类型或方法中的类型参数'TRequest’。

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

Stack Overflow用户
提问于 2022-01-10 14:53:20
回答 2查看 7.2K关注 0票数 23

我使用MediatR在我的应用程序中使用IPipelineBehavior<TRequest, TResponse>进行请求响应日志记录

代码示例:

代码语言:javascript
运行
复制
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之后,我开始得到下面的编译错误。

类型'TRequest‘不能用作泛型类型或方法'IPipelineBehavior’中的类型参数'TRequest‘。没有从“TRequest”到“MediatR.IRequest”的装箱转换或类型参数转换

我设法从官方的移植指南回购中找到了MediatR。但找不到任何例子。

我是不是漏了什么东西,能不能有人帮我一下?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-01-10 14:57:33

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

代码语言:javascript
运行
复制
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...
}
票数 68
EN

Stack Overflow用户

发布于 2022-06-21 21:03:16

根据Github文档,这是必需的https://github.com/jbogard/MediatR/wiki/Migration-Guide-9.x-to-10.0

其中TRequest : IRequest

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70654329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档