Предположим, у меня есть интерфейс:
public interface ISomeInterface
{
bool SomeBool { get; set; }
string ValueIfSomeBool { get; set; }
}
И у меня есть ряд классов, которые реализуют это. то есть
public class ClassA : ISomeInterface
{
#region Implementation of ISomeInterface
public bool SomeBool { get; set; }
public string ValueIfSomeBool { get; set; }
#endregion
[NotNullValidator]
public string SomeOtherClassASpecificProp { get; set; }
}
И у меня есть логика Validation для свойств этого интерфейса в пользовательском валидаторе, например:
public class SomeInterfaceValidator : Validator
{
public SomeInterfaceValidator (string tag)
: base(string.Empty, tag)
{
}
protected override string DefaultMessageTemplate
{
get { throw new NotImplementedException(); }
}
protected override void DoValidate(ISomeInterface objectToValidate, object currentTarget, string key, ValidationResults validationResults)
{
if (objectToValidate.SomeBool &&
string.IsNullOrEmpty(objectToValidate.ValIfSomeBool))
{
validationResults.AddResult(new ValidationResult("ValIfSomeBool cannot be null or empty when SomeBool is TRUE", currentTarget, key, string.Empty, null));
}
if (!objectToValidate.SomeBool &&
!string.IsNullOrEmpty(objectToValidate.ValIfSomeBool))
{
validationResults.AddResult(new ValidationResult("ValIfSomeBool must be null when SomeBool is FALSE", currentTarget, key, string.Empty, null));
}
}
}
И у меня есть атрибут для применения этого валидатора, который я украшаю ISomeInterface.
[AttributeUsage(AttributeTargets.Interface)]
internal class SomeInterfaceValidatorAttribute : ValidatorAttribute
{
protected override Validator DoCreateValidator(Type targetType)
{
return new SomeInterfaceValidator(this.Tag);
}
}
Когда я вызываю Validation.Validate, похоже, что он не запускает проверку в SomeInterfaceValidator. Он выполняет проверку, специфичную для ClassA, но не связанную с интерфейсом ISomeInterface.
Как мне заставить это работать?
EDIT:
I found one way to get this to work and that is to do SelfValidation, where I cast to ISomeInterface and validate like so. This will suffice, but still leaving the question open to see if there are any other ways to accomplish this.
[SelfValidation]
public void DoValidate(ValidationResults results)
{
results.AddAllResults(Validation.Validate((ISomeInterface)this));
}