我有一个场景,我想使用反射来使用 Fluent Validation 进行验证。像这样的事情:
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...
});
}
}
}
致电给ReflectionHelper.GetShallowPropertiesInfo(obj)
返回对象的“浅”属性。然后,我为每个属性创建一条规则。
这是我获取对象属性的代码:
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;
}
}
这段代码编译并可以执行
IValidator<Foo> validator = new FooValidator(foo);
var results = validator.Validate(foo);
但它无法正常工作(验证永远不会失败)。有什么办法可以实现这一点吗?
注意:演示代码可以在 Github 上找到FluentValidation 反思 https://github.com/josmonver/FluentValidationReflection
最后我找到了一个有效的解决方案。我创建了一个接收 PropertyInfo 参数的自定义 PropertyValidator:
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...
}
}
以及一个扩展方法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));
}
}
有了这个我可以改变我的FooValidator
如下:
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...
});
}
}
}
现在我可以使用反射为特定属性添加规则
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)