我将MediatR与以下类一起使用:
public class GetPostsRequest : IRequest<Envelope<GetPostsResponse>> {
public Int32 Age { get; set; }
}
public class GetPostResponse {
public String Title { get; set; }
public String Content { get; set; }
}
其中 Envelope 是一个包装类:
public class Envelope<T> {
public List<T> Result { get; private set; } = new List<T>();
public List<Error> Errors { get; private set; } = new List<Error>();
}
由中介发送的 GetPostsRequest 由 Handler 执行:
public class GetPostsRequestHandler : IRequestHandler<GetPostsRequest, Envelope<GetPostsResponse>> {
public async Task<Envelope<GetPostsResponse>> Handle(GetPostsRequest request, CancellationToken cancellationToken) {
}
}
MediatR 允许使用在特定请求的处理程序之前执行的行为。我创建了一个ValidationBehavior如下:
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, Envelope<TResponse>>
where TRequest : IRequest<Envelope<TResponse>> {
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators) {
_validators = validators;
}
public Task<Envelope<TResponse>> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<Envelope<TResponse>> next) {
ValidationContext context = new ValidationContext(request);
List<Error> errors = _validators
.Select(x => x.Validate(context))
.SelectMany(x => x.Errors)
.Select(x => new Error(ErrorCode.DataNotValid, x.ErrorMessage, x.PropertyName))
.ToList();
if (errors.Any())
return Task.FromResult<Envelope<TResponse>>(new Envelope<TResponse>(errors));
return next();
}
}
我在 ASP.NET Core 应用程序上注册了 ValidationBehavior:
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
当我调用 API 时,出现以下错误:
An unhandled exception has occurred while executing the request.
System.ArgumentException: GenericArguments[0], 'TRequest', on 'ValidationBehavior`2[TRequest,TResponse]' violates the constraint of type 'TRequest'.
---> System.TypeLoadException: GenericArguments[0], 'TRequest', on 'ValidationBehavior`2[TRequest,TResponse]' violates the constraint of type parameter 'TRequest'.
我错过了什么?