How to use Reflection in FluentValidation?

无人久伴 提交于 2021-02-06 13:55:15

问题


I have a scneario in which I want to use reflection to do validation using FluentValidation. Someting like this:

public class FooValidator : AbstractValidator<Foo>
{
    public FooValidator(Foo obj)
    {
        // Iterate properties using reflection
        var properties = ReflectionHelper.GetShallowPropertiesInfo(obj);
        foreach (var prop in properties)
        {
            // Create rule for each property, based on some data coming from other service...
            //RuleFor(o => o.Description).NotEmpty().When(o => // this works fine when foo.Description is null
            RuleFor(o => o.GetType().GetProperty(prop.Name)).NotEmpty().When(o =>
            {
                return true; // do other stuff...
            });
        }
    }
}

The call to ReflectionHelper.GetShallowPropertiesInfo(obj) returns "shallow" properties of object. Then, for each property I create a rule. This is my code for get properties of object:

public static class ReflectionHelper
{
    public static IEnumerable<PropertyInfo> GetShallowPropertiesInfo<T>(T o) where T : class
    {

        var type = typeof(T);
        var properties =
            from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
            where pi.PropertyType.Module.ScopeName == "CommonLanguageRuntimeLibrary"
                && !(pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>))
            select pi;

        return properties;
    }
}

This code compile and can be executed

IValidator<Foo> validator = new FooValidator(foo);
var results = validator.Validate(foo);

But it doesn't work properly (validation never fails). Is there any way to achieve this?

Note: Demo code can be found int Github at FluentValidationReflection


回答1:


Finally I've found a solution that works. I've created a custom PropertyValidator that receives a PropertyInfo parameter:

public class CustomNotEmpty<T> : PropertyValidator
{
    private PropertyInfo _propertyInfo;

    public CustomNotEmpty(PropertyInfo propertyInfo)
        : base(string.Format("{0} is required", propertyInfo.Name))
    {
        _propertyInfo = propertyInfo;
    }

    protected override bool IsValid(PropertyValidatorContext context)
    {
        return !IsNullOrEmpty(_propertyInfo, (T)context.Instance);
    }

    private bool IsNullOrEmpty(PropertyInfo property, T obj)
    {
        var t = property.PropertyType;
        var v = property.GetValue(obj);

        // Omitted for clarity...
    }
}

And a extension method for IRuleBuilder:

public static class ValidatorExtensions
{
    public static IRuleBuilderOptions<T, T> CustomNotEmpty<T>(
        this IRuleBuilder<T, T> ruleBuilder, PropertyInfo propertyInfo)
    {
        return ruleBuilder.SetValidator(new CustomNotEmpty<T>(propertyInfo));
    }
}

With this I can change my FooValidator as follows:

public class FooValidator : AbstractValidator<Foo>
{
    public FooValidator(Foo obj)
    {
        // Iterate properties using reflection
        var properties = ReflectionHelper.GetShallowPropertiesInfo(obj);
        foreach (var prop in properties)
        {
            // Create rule for each property, based on some data coming from other service...
            RuleFor(o => o)
                .CustomNotEmpty(obj.GetType().GetProperty(prop.Name))
                .When(o =>
            {
                return true; // do other stuff...
            });
        }
    }
}

And now I'm be able to use Reflection to add rules for specific properties



来源:https://stackoverflow.com/questions/35871741/how-to-use-reflection-in-fluentvalidation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!