MediatR PipelineBehavior 错误消息无法解析类型“FluentValidation.IValidator”1 的服务

发布于 2025-01-12 09:39:29 字数 1644 浏览 0 评论 0原文

我有这个 ValidationBehavior

public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IValidator<TRequest> _validator;

    public ValidationBehavior(IValidator<TRequest> validator)
    {
        _validator = validator;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        _validator.ValidateAndThrow(request);
        return await next();
    }
}  

我有这个处理程序,

public class RemoveCurrencyHandler : IRequestHandler<RemoveCurrencyCommand, Unit>
{
    private readonly ApplicationContext _context;

    public RemoveCurrencyHandler(ApplicationContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(RemoveCurrencyCommand request, CancellationToken cancellationToken)
    {
        var currency = await _context.Currency.FindAsync(request.Id);

        if (currency is null)
            throw new KeyNotFoundException();

        _context.Remove(currency);
        await _context.SaveChangesAsync();
        return Unit.Value;
    }
}  

每次我调用这个处理程序时,我都会收到错误消息无法解析类型“FluentValidation.IValidator”的服务,现在显然我知道原因是因为我缺少验证器,所以如果我添加此验证器,它就会消失,

public class RemoveCurrencyValidator : AbstractValidator<RemoveCurrencyCommand>
{

}  

但并非所有处理程序都需要 Validator,所以我不想添加空的 Validator > 类到处理程序那不需要它。还有其他选择吗?

I have this ValidationBehavior

public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IValidator<TRequest> _validator;

    public ValidationBehavior(IValidator<TRequest> validator)
    {
        _validator = validator;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        _validator.ValidateAndThrow(request);
        return await next();
    }
}  

I have this handler

public class RemoveCurrencyHandler : IRequestHandler<RemoveCurrencyCommand, Unit>
{
    private readonly ApplicationContext _context;

    public RemoveCurrencyHandler(ApplicationContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(RemoveCurrencyCommand request, CancellationToken cancellationToken)
    {
        var currency = await _context.Currency.FindAsync(request.Id);

        if (currency is null)
            throw new KeyNotFoundException();

        _context.Remove(currency);
        await _context.SaveChangesAsync();
        return Unit.Value;
    }
}  

I'm getting error message Unable to resolve service for type 'FluentValidation.IValidator' everytime I call this handler, now obviously I know the reason is because I'm missing the validator, so it goes away if I add this

public class RemoveCurrencyValidator : AbstractValidator<RemoveCurrencyCommand>
{

}  

but not all my handler need a Validator, so I don't want to add empty Validator class to handler that doesn't need it. Is there any alternative?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

病女 2025-01-19 09:39:29

MediatR 验证器 pipelines 使您能够在命令或查询处理程序执行之前和之后执行验证逻辑。
您可以更新 ValidationBehavior 类的构造函数以获取 IEnumerable。这样我们就可以随时解析该类(如果您不实现Validator,列表将为空)

// ValidationBehavior
public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IEnumrable<IValidator<TRequest>> _validators;

    public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        if(_validators.Any())
        {
            var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAndThrow(request)));

            var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
            if (failures.Count != 0)
                throw new ValidationException(failures);
        }
        return await next();
    }
} 

The MediatR validator pieplines enable you to execute validation logic before and after your Command or Query Handlers execute.
You can update the constructor of ValidationBehavior class to expect an IEnumerable<IValidator>. So that we can always resolve the class (the list will be empty if you don't implement the Validator)

// ValidationBehavior
public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IEnumrable<IValidator<TRequest>> _validators;

    public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        if(_validators.Any())
        {
            var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAndThrow(request)));

            var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
            if (failures.Count != 0)
                throw new ValidationException(failures);
        }
        return await next();
    }
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文