Custom Validation and Dependencies

Topics: General, Writing modules
Dec 31, 2011 at 7:41 PM

Hi all,

I have a custom validation method defined in a class called SignUpModelValidation. The validation method needs access to my ICourseService. Is there a way to have Orchard inject that dependency to the validation? Or is the better way to just include ALL necessary fields for validation on the actual object being validated?

For instance, have a view mode (SignUpViewModel)l with a CoursePart property and a NumberOfAttendees property.
I have ICourseService that can return the current number of registrations for a course.

In my validatio I need to check if
NumberOfAttendees <= CoursePart.TotalSeats - courseService.GetNumberOfRegistrations()

But, since validation methods are static and static classes can't have instance constructors I'm not sure how to cleanly get ICourseService injected to the validator.

Maybe just adding an OpenSeats property to the view model is the better way?

Thanks,
Will

Coordinator
Dec 31, 2011 at 8:07 PM

In principle, your validators should be, much like a view, doing just validation and be initialized from the start with all the data that it needs. When you construct that validator, just give it has all it needs to do its job. Am I making any sense?

Dec 31, 2011 at 8:20 PM
Edited Dec 31, 2011 at 8:20 PM

Absolutely, this is what I ended up going with. Thanks for the input! This actually has other implications, specifically on performance and maintainability.
Injecting the services (if it were even possible) would mean priming the data multiple times.
The service that creates the view model has already done that work so why do it again.

I was approaching from a point of view that ViewModels should contain ONLY the data needed for the dependent view. I guess this IS necessary data, even though it isn't displayed on the view. Semantics...

Thanks Bertrand
As always, you are very helpful!

Will

P.S. I'm nearing completing with this new site and I'll pass along the URL once it goes public.
For this site I've done integration with Authorize.Net 2 different ways (client decided to opt for SIM instead of a custom form due to PCI concerns). This was definitely a learning experience and, as my other projects, I leave in total awe of what Orchard is capable of.
You guys are doing a fantastic job with it!