Question

I'm wondering if anyone knows if xVal will work as expected if I define my system.componentmodel.dataannotations attributes on interfaces that are implemented by my model classes, instead of directly on the concrete model classes.

public interface IFoo
{
    [Required] [StringLength(30)]
    string Name { get; set; }
}

and then in my model class there wouldn't be any validation attributes...

public class FooFoo : IFoo
{
    public string Name { get; set; }
}

If I try to validate a FooFoo with xVal, will it use the attribs from its interface?

Was it helpful?

Solution

At the moment the xVal.RuleProviders.DataAnnotationsRuleProvider only looks at properties defined on the model class itself. You can see this in the method GetRulesFromProperty in the rule provider base class PropertyAttributeRuleProviderBase:

protected virtual IEnumerable<Rule> GetRulesFromProperty(
    PropertyDescriptor propertyDescriptor)
{
    return from att in propertyDescriptor.Attributes.OfType<TAttribute>()
           from validationRule in MakeValidationRulesFromAttribute(att)
           where validationRule != null
           select validationRule;
}

The propertyDescriptor parameter represents a property in your model class and its Attributes property represents only the attributes defined directly on the property itself.

However, you could of course extend DataAnnotationsRuleProvider and override the appropriate method to make it do what you want: extract validation attributes from implemented interfaces. You then register your rule provider with xVal:

ActiveRuleProviders.Providers.Clear();
ActiveRuleProviders.Providers.Add(new MyDataAnnotationsRuleProvider());
ActiveRuleProviders.Providers.Add(new CustomRulesProvider());

To get attributes from properties in implemented interfaces, you should extend DataAnnotationsRuleProvider and override GetRulesFromTypeCore. It gets a parameter of type System.Type that has a method GetInterfaces.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top