asp.net-core-webapimediatr

ASP.NET Core - Error CS0535 'PerformanceBehaviour<TRequest, TResponse>' does not implement interface member 'IPipelineBehavior


In ASP.NET Core-8 With MediatR I got this error:

Error CS0535 'PerformanceBehaviour<TRequest, TResponse>' does not implement interface member 'IPipelineBehavior<TRequest, TResponse>.Handle(TRequest, RequestHandlerDelegate, CancellationToken)'

It highlights:

IPipelineBehavior<TRequest, TResponse>

PerformanceBehaviour:

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;
        }

        public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            _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;
        }
    }
}

Solution

  • It looks like you might have conflicting versions of MediatR?

    v10 of the interface method has the CancellationToken in the middle, just like your code.

    Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next);
    

    But v11 changed this to have the CancellationToken at the end of the method signature.

    Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken);
    

    The error indicates the latter form, but your code indicates the former.