c# - 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);
感谢您的任何建议
解决方案
推荐阅读
- javascript - 如何在 div 元素中显示新行?
- cpu-architecture - 我如何知道我正在查看的是 CISC 还是 RISC 指令集?
- javascript - 如何通过道具使地图功能内的子值可编辑
- javascript - 如何导入功能组件?
- lucene - 在 Lucene 中高效地执行批量精确匹配查找?
- html - 如何为 html 网站上的文本添加对比度?
- java - 如何在不阻塞的情况下从 Spring Webflux 中的 Mono 对象中提取数据?
- ios - React Native 图像未在较新版本的 iOS 上呈现
- excel - 使用超过 2 个 IF 条件来识别混合列中的不同数据类型 - Power Query
- jquery - Ruby on rails + jquery - 如何使用