FluentValidation中调用派生验证器不存在的规则集,验证会失败吗?
问题解答
场景背景
领域模型
public abstract class BaseItem { // Base class implementation... } public class FooItem : BaseItem { // Derived Class A implementation... } public class BarItem : BaseItem { // Derived Class B implementation... }
FluentValidation验证器
public class BaseItemValidator : AbstractValidator<BaseItem> { public BaseItemValidator() { // Rules for Base Item } } public class FooItemValidator : AbstractValidator<FooItem> { public FooItemValidator() { Include(new BaseItemValidator()); RuleSet("FooRules", () => { // Rules for derived FooItem instances }); } } public class BarItemValidator : AbstractValidator<BarItem> { public BarItemValidator() { Include(new BaseItemValidator()); } }
泛型服务
public class BarItemService<T> { private IValidator<T> _validator; public BarItemService(IValidator<T> validator) { _validator = validator; } public async Task AddItem(T item, CancellationToken token = default) { var result = await _validator.ValidateAsync(item, opt => opt.IncludeRuleSets("FooRules"), token); if (!result.IsValid) { // Indicate the item is not valid } // Rest of the method... } }
问题
当T为BarItem时,调用AddItem方法尝试引用FooItem专属的规则集,验证会失败吗?
解答
不会失败,验证会正常通过,原因如下:
- 当T是BarItem时,注入的验证器是
BarItemValidator,该验证器中并未定义名为"FooRules"的规则集。 - FluentValidation在指定不存在的规则集时,不会抛出异常,也不会判定验证无效——它只会跳过这些不存在的规则集,仅执行当前验证器中存在的规则(即
BaseItemValidator里的基础验证规则)。 - 只要BarItem实例符合BaseItem的验证规则,
result.IsValid就会返回true,不会进入验证失败的分支。
内容的提问来源于stack exchange,提问作者Matt Rogan
相关产品推荐
相关产品推荐

