views:

193

answers:

1

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?

+3  A: 

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.

Ronald Wildenberg
Thanks for the detailed answer!! I guess the next question is: Is there an easy way to iterate through the interfaces a class implements? You would need to do this in order to get PropertyDescriptors for each property on the interfaces.
NathanD
I added some more info on how to get the implemented interfaces of a type.
Ronald Wildenberg
Looks pretty straightforward, Thanks a bunch!!
NathanD