MVC / DataAnnotations.ValidationAttribute

Sep 28, 2014 at 3:54 PM
Hi All,

My MVC models are pretty complex, and they come with some pretty heavy validators (for example, I have to use COM interop to interact with Certificate Authorities to validate certificate signing requests).
I'm trying to get my main logger injected into the validation classes, without much success.
Currently, the validators are structured along these lines:

public class BaseValidator : ValidationAttribute
{
...some fields/properties
[Import]
public Logger Logger {get;set;}
}

public Validator1 : BaseValidator
{
....
Logger.Info <-- is null
}

Am I missing something obvious here? Any better options?

Thanks,
Luca
Coordinator
Sep 28, 2014 at 4:09 PM
Edited Oct 21, 2014 at 5:45 PM
Hi Luca,

Simple Injector contains an extension method in the MVC integration package that allows initialization/injection on MVC filter attributes. DataAnnotations however has nothing to do with MVC filter attributes and that mechanism will therefore not touch your validation attributes.

To allow complex business logic in validation attributes, Microsoft designed the Validation attributes to use the IServiceProvider abstraction. This allows querying the IServiceProvider for services that are registered in the container.

Doing this however is a terrible idea, because this leads to the Service Locator anti-pattern. Or more specific, attributes with logic is a terrible idea, as I explained here and Mark Seemann explained here.

Instead, such specific business validation deserves its own abstraction. In the applications I build, I define an IValidator<T> abstraction. Here the T is the type of object to validate. I use this in combination with my commands and command handlers where I specify one or multiple IValidator<T> implementations for a certain command. These validations are triggered inside a command handler decorator just before the real business logic is executed. But the exact design that suits you best depends on a lot of factors of course, but best is to keep logic out of attributes.
Marked as answer by dot_NET_Junkie on 11/3/2014 at 1:26 AM
Sep 28, 2014 at 6:53 PM
Thank you!...I'll go thru the links, seems i'll need to do a major re-write of these attributes:)

Luca