我使用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
之后,我开始得到下面的编译错误。
类型'TRequest‘不能用作泛型类型或方法'IPipelineBehavior’中的类型参数'TRequest‘。没有从“TRequest”到“MediatR.IRequest”的装箱转换或类型参数转换
我设法从官方的移植指南回购中找到了MediatR
。但找不到任何例子。
我是不是漏了什么东西,能不能有人帮我一下?
发布于 2022-01-10 14:57:33
您还需要在抽象类中指定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...
}
发布于 2022-06-21 21:03:16
根据Github文档,这是必需的https://github.com/jbogard/MediatR/wiki/Migration-Guide-9.x-to-10.0。
其中TRequest : IRequest
https://stackoverflow.com/questions/70654329
复制相似问题