如何使用流畅验证来验证包含更多相同类型对象的对象?

Ros*_*oss 5 .net asp.net-mvc fluentvalidation

我有一个Action类,它包含更多Action对象的集合.像这样的东西:

public class Action
{
    ICollection<Action> SubActions;
}
Run Code Online (Sandbox Code Playgroud)

这基本上形成了一个树形结构(我确保没有循环).我使用Fluent Validation为这个类编写验证器.这是我的Validator尝试:

public class ActionValidator : AbstractValidator<Action>
{
    public ActionValidator()
    {
        RuleFor(x => x.SubActions).SetCollectionValidator(new ActionValidator());
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试解决依赖于ActionValidator的任何事情时,Unity会爆炸.更具体地说,LINQPad在尝试解析依赖于ActionValidator的服务时崩溃,可能是来自堆栈溢出.

在我的Action类中还有其他成员我正在验证,但我只是为了简洁起见重要部分.如果我注释掉我在这里列出的规则,它可以正常工作(除了它不再验证子动作).

我的方法遇到了问题.我递归地构造验证器直到某些东西死亡.但我只是不确定如何告诉Fluent Validation以这种方式验证子对象.

Ros*_*oss 12

将验证相同类型的规则更改为:

Rulefor(x => x.SubActions).SetCollectionValidator(this);
Run Code Online (Sandbox Code Playgroud)

  • 我花了很长时间才弄清楚。难过,真的。 (2认同)