title: DataAnnotations CustomValidator with Generic Type
body: <p>This is an MVC 3 project using S#arp Architecture.</p>
  
  <p>My domain has several objects that inherit <code>NamedEntity</code> which is an abstract class extending <code>Entity</code> and defining a <code>string Name</code> property.</p>
  
  <p>All of these objects share the fact that they must be unique names across their object type.</p>
  
  <p>Given that the sets of these objects will be relatively small (200 would be an extreme case), I don't mind the round-trip to the database to check if there's a duplicate.</p>
  
  <p>My question is, <strong>what is the best way to easily validate this while keeping to DRY?</strong></p>
  
  <p>I've gone through a half-dozen iterations, not particularly liking any of them. I've tried creating a <code>[ValidUniqueName]</code> attribute on the ViewModel, and the ViewModel can be typed <code>EditViewModel&lt;T&gt; where T: NamedEntity</code>. The problem comes that the attribute doesn't know the correct repository / tasks object to talk to because of the Generic. </p>
  
  <p>To work around that, I tried creating a <code>INamedEntityTasks&lt;T&gt;</code> reference in the ViewModel, and accessing it from the <code>ValidationContext</code> for the <code>ValidUniqueName</code> attribute. That doesn't work as expected, because the Attribute isn't generic (it can't be) and therefore it doesn't know how to properly cast the <code>ValidationContext.ObjectInstance</code> back into something usable.</p>
  
  <p>At this point, the only thing I can think of is to create separate <code>[ValidUniqueFoo]</code> <code>[ValidUniqueBar]</code> etc. attributes, which seems bad. Alternatively, I can put the validation in each controller, but that's equally bad it seems.</p>