MediatR
MediatR copied to clipboard
Failed to convert a generic implementation for IPipelineBehavior
I have implemented a generic pipeline behavior for my query handlers like the one below:
public sealed class ErrorHandlerBehaviour<TRequest, TResponse>
: IPipelineBehavior<TRequest, ViewResult<TResponse>>
{
public async Task<ViewResult<TResponse>> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<ViewResult<TResponse>> next)
{
return ViewResult.Fail();
}
}
and registered that in the container like:
services.Add( new ServiceDescriptor(
typeof(IPipelineBehavior<,>), typeof(ErrorHandlerBehaviour<,>),
context.ServiceLifetime));
I have defined a query and a query handler:
public class GetStudent : IRequest<ViewResult<Student>>
{
public Guid Id { get; set; }
public bool ThrowError { get; set; }
}
public class GetStudentHandler : IRequestHandler<GetStudent, ViewResult<Student>>
{
public async Task<ViewResult<Student>> Handle(GetStudent request, CancellationToken cancellationToken)
{
if( request.ThrowError ) throw new ModelNotFoundException();
return new Student(request.Id);
}
public IViewContext ViewContext { get; }
}
but at the runtime when I want to send the query to via mediator instance I get the following error:
Implementation type 'ErrorHandlerBehaviour`2[GetStudent,ViewResult`1[Student]]' can't be converted to service type 'MediatR.IPipelineBehavior`2[GetStudent,ViewResult`1[Student]]
however when I explicitly define a pipeline behavior for that query handler it works but the generic one does not, is there something I have missed?