我已经为我的查询处理程序实现了一种通用的管道行为,如下所示:
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();
}
}
并将其注册在容器中,例如:
services.Add(new ServiceDescriptor(
typeof(IPipelineBehavior<,>),
typeof(ErrorHandlerBehaviour<,>),
context.ServiceLifetime));
我已经定义了一个查询和一个查询处理程序:
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; }
}
但是在运行时,当我想通过中介实例将查询发送到时,我收到以下错误:
实现类型“ErrorHandlerBehaviour
2[GetStudent,ViewResult1[Student]]”无法转换为服务类型“MediatR.IPipelineBehavior2[GetStudent,ViewResult1[Student]]
但是,当我为该查询处理程序明确定义管道行为时,它可以工作,但通用的却没有,我错过了什么吗?