如何根据属性的运行时类型动态选择验证器?

时间:2016-11-04 21:55:49

标签: c# fluentvalidation

给定一个具有泛型参数的基类,该参数用于定义属性的类型并且对另一个基类型有限制,在为派生类编写Fluent验证器时,该验证器如何切换哪个子验证器是适用于通用属性?

以下是一些演示此配置的示例类:

public abstract class BaseParent<TChildType> where TChildType : BaseChild
{
    public TChildType Child {get; set;}
}

public abtract class BaseChild
{
    public sting ChildPropOne {get; set;}
}

public class ChildA : BaseChild
{
    public string ChildAPropOne {get; set;}
}

public class ChildB: BaseChild
{
    public string ChildBPropOne {get; set;}
}

public class ParentA<TChildType> : BaseParent<TChildType> where TChildType : BaseChild
{
    public string ParentAPropOne {get; set;}
}

public class ParentB<TChildType> : BaseParent<TChildType> where TChildType : BaseChild
{
    public string ParentBPropOne {get; set;}
}

我当前的设置为每个父类型+子类型组合强制使用不同的验证器类。理想情况下,我可以为每个父项编写一个验证程序,每个子程序编写一个验证程序,并让父验证程序能够选择要调用的子验证程序

1 个答案:

答案 0 :(得分:2)

您可以将child的验证器实例注入父级验证器,并使用SetValidator Child属性:

public class ParentAValidator<TChildType> : AbstractValidator<ParentA<TChildType>> where TChildType : BaseChild
{
    public ParentAValidator(IValidator<TChildType> childValidator)
    {
        RuleFor(p => p.Child).SetValidator(childValidator);
    }
}