我正在使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是升级到之后Nuget - v10.0.0我开始收到以下编译错误。
类型“TRequest”不能用作通用类型或方法“IPipelineBehavior<TRequest, TResponse>”中的类型参数“TRequest”。没有从“TRequest”到“MediatR.IRequest”的装箱转换或类型参数转换
我设法从官方仓库找到了移植指南MediatR。但找不到任何例子。
我还缺少其他东西吗,有人可以帮助我吗?
msm*_*cic 79
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...
}
Run Code Online (Sandbox Code Playgroud)