开发者

How do I use fluent validation to validate an object which contains more objects of the same type?

开发者 https://www.devze.com 2023-03-29 01:31 出处:网络
I have a class Action which h开发者_运维问答as a collection of more Action objects. Something like this:

I have a class Action which h开发者_运维问答as a collection of more Action objects. Something like this:

public class Action
{
    ICollection<Action> SubActions;
}

This basically forms a tree structure (I make sure there are no cycles). I used Fluent Validation to write a validator for this class. Here is my Validator attempt:

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

Unity blows up when I try to resolve anything which depends on ActionValidator. More specifically, LINQPad crashes when it tries to resolve a service which depends on ActionValidator, presumably from a stack overflow.

There are other members in my Action class that I'm validating, but I've just put the important part for brevity. If I comment out the rule I've listed here, it works fine (except it's not validating subactions anymore).

I get the problem with my approach. I'm recursively constructing validators until something dies. But I'm just not sure how I'm to tell Fluent Validation to validate sub-objects this way.


Change the rule that validates the same type to:

Rulefor(x => x.SubActions).SetCollectionValidator(this);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号