One common approach (if you own both Customer
and CustomerValidator
) is to decorate the class with the class that provides validation, via an attribute:
[Validator(typeof(CustomerValidator))]
public class Customer { }
Note that you may find it easier to work outside of generics, perhaps via an interface (note: no methods etc shown here):
public interface IValidator { }
public class CustomerValidator : AbstractValidator<Customer> {}
public class AbstractValidator<T> : IValidator where T : class {}
Then obtain the correct validator via reflection:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidatorAttribute : Attribute
{
public Type ValidatorType { get; private set; }
public ValidatorAttribute(Type validatorType)
{
ValidatorType = validatorType;
}
public static IValidator GetValidator(object obj)
{
if (obj == null) return null;
return GetValidator(obj.GetType());
}
public static IValidator GetValidator(Type type)
{
if (type == null) return null;
ValidatorAttribute va = (ValidatorAttribute)
Attribute.GetCustomAttribute(type, typeof(ValidatorAttribute));
if (va == null || va.ValidatorType == null) return null;
return (IValidator) Activator.CreateInstance(va.ValidatorType);
}
}
So calling GetValidator
should return null
or a suitable IValidator
.
You can use generics in the above - but it usually creates more problems than it solves in example like this.