ASP.NET Core 8+MediatR报错CS0535:PerformanceBehaviour未实现接口成员
解决MediatR编译错误CS0535的方案
这个错误是因为MediatR v10+版本调整了IPipelineBehavior<TRequest, TResponse>.Handle方法的参数顺序,你的代码里参数顺序和接口定义不匹配,导致编译器判定未实现接口成员。
问题根源
旧版MediatR的Handle方法参数顺序是:Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
而MediatR v10及以后的版本,接口定义的参数顺序改为:Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
你的代码沿用了旧的参数顺序,和新版本接口不兼容。
修复步骤
调整Handle方法的参数顺序,把RequestHandlerDelegate<TResponse> next移到第二个位置,CancellationToken cancellationToken放在最后。
修正后的代码:
using MediatR; using Microsoft.Extensions.Logging; using System.Diagnostics; namespace SpecMaker.Application.Common.Behaviours { public class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse> { private readonly Stopwatch _timer; private readonly ILogger<TRequest> _logger; public PerformanceBehaviour(ILogger<TRequest> logger) { _timer = new Stopwatch(); _logger = logger; } // 调整参数顺序:next放在第二个位置,cancellationToken在最后 public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) { _timer.Start(); var response = await next(); _timer.Stop(); var elapsedMilliseconds = _timer.ElapsedMilliseconds; if (elapsedMilliseconds > 600) { var requestName = typeof(TRequest).Name; var userName = string.Empty; _logger.LogWarning("SpecMaker Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@Request}", requestName, elapsedMilliseconds, request); } return response; } } }
内容的提问来源于stack exchange,提问作者Gbenga
相关产品推荐
相关产品推荐

