Hi!
I started with ServiceStack the last days and reached the validation part today.
FluentValidation is a really nice validation lib.
I had to test this kind of polymorphism too, but i decided to do it with just one entity instead of a collection. I started using your sample code.
So you can create the exact same validators (base and inherited validators) and use them.
In my version, u just need to register them once with the PolymorphicAutoValidator:
Its up to you to implement the default Validator if the type is not defined.
I also could think of a mechanism scanning an assembly and registering all types of IValidator once. This would remove the requirement of registering each derived validator.
I started with ServiceStack the last days and reached the validation part today.
FluentValidation is a really nice validation lib.
I had to test this kind of polymorphism too, but i decided to do it with just one entity instead of a collection. I started using your sample code.
So you can create the exact same validators (base and inherited validators) and use them.
In my version, u just need to register them once with the PolymorphicAutoValidator:
PolymorphicAutoValidator.RegisterDerivedValidator(new HR.RoBP.Contracts.Validators.Model.EmployeeValidator());
`
So you end up with: RuleFor(r => r.PropertyWithABaseTypeOfPerson).SetValidator(new PolymorphicAutoValidator());
If the Property PropertyWithABaseTypeOfPerson is an Employee class, its validated with the registered EmployeeValidator.Its up to you to implement the default Validator if the type is not defined.
I also could think of a mechanism scanning an assembly and registering all types of IValidator once. This would remove the requirement of registering each derived validator.
public class PolymorphicAutoValidator: NoopPropertyValidator
{
private static readonly Dictionary<Type, IValidator> DerivedValidators = new Dictionary<Type, IValidator>();
public static void RegisterDerivedValidator<TDerived>(IValidator<TDerived> derivedValidator)
{
DerivedValidators.Add(typeof(TDerived),derivedValidator);
}
public override IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context)
{
var type = context.PropertyValue.GetType();
if (DerivedValidators.ContainsKey(type))
{
var validator = new ChildValidatorAdaptor(DerivedValidators[type]);
return validator.Validate(context);
}
return null;
}
}
```