首页 > 解决方案 > FluentValidation - RuleForEach 的 SetAsyncValidator

问题描述

我是 RuleForeach 内的 SetAsyncValidator 验证集合的问题。我需要异步验证器,因为我需要检查记录是否已经存在。

我在异步模式下使用 Mediatr 验证的管道。

网上冲浪我还没有找到类似的场景。我怎么能意识到这一点? 产品类别类

public class ProductCategory : AuditableEntity, IAggregateRoot
{
    public string Name { get; private set; }

    private List<ProductSubCategory> _productSubCategories;

    //public IEnumerable<ProductSubCategory> ProductSubCategories => _productSubCategories.AsReadOnly();
    public List<ProductSubCategory> ProductSubCategories => _productSubCategories;
    public ProductCategory()
    {
        _productSubCategories = new List<ProductSubCategory>();
    }

    public void AddProductSubcategory(string name)
    {
        var productSubCategory = new ProductSubCategory(name);
        _productSubCategories.Add(productSubCategory);
    }
}

public class ProductSubCategory : AuditableEntity, IAggregateRoot
{
    public string Name { get; private set; }

    public ProductSubCategory(string name)
    {
        Name = name;
    }

    public ProductSubCategory()
    {
    }
}

这是同步规则,效果很好,但我想异步运行

When(x => x.ProductSubCategories.Any(), () =>
{
    RuleForEach(x => x.ProductSubCategories).SetValidator(new CreateProductSubCategoryCommandValidator(_repositorySub));
});

验证管道:处理方法

        public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var typeName = request.GetGenericTypeName();

        _logger.LogDebug("----- Validating command {CommandType}", typeName);

        if (!_validators.Any()) 
            return await next();
        
        var context = new ValidationContext<TRequest>(request);
        var validationResults = await Task.WhenAll(_validators
            .Select(v => v.ValidateAsync(context, cancellationToken)));
        
        var failures = validationResults.SelectMany(r => r.Errors)
            .Where(f => f != null)
            .ToList();

        if (failures.Count == 0) 
            return await next();
        
        _logger.LogDebug("----- Validating command {typeName} with failures {@failures}", typeName, failures );
        throw new ValidationException(failures);

感谢您的任何建议

标签: c#asynchronousfluentvalidation

解决方案


推荐阅读