Pass Parameters to the Validate function

Apr 12, 2010 at 7:18 AM

The Validate() function of ValidationAspects works very nicely when you have all the necessary data within the object that is being validated. In our project we had scenarios wherein we needed to use other objects (that are not a part of the validated object) to perform the validation. Ideally, all that I wanted was the ability to pass parameters to the Validate( ) function. These parameters will be used by the functions marked with the [ValidationMethod] attribute.

E.g. We are using NHibernate and the validated object is persisted in the database. The object needs to be validated to ensure that the 'Name' property is unique. For this, I need to use the a Provider object which enables me to identify if the property is unique or not. 
There are alternative methods to achieve this - one of them is to add the required objects to the class (I did not want to do that as that would unnecessarily bloat my class).

I therefore, decided to modify ValidationAspects to take in arguments in the Validate( ) function.

How does it work ???

Validate( ) function is now overloaded to take in an IDictionary<string, object> argument. It allows you to pass any type of object to the method marked as [ValidationMethod] in the class.

The [ValidationMethod] functions should have the signature as public static void <methodName> (<ValidationClassName> variable, IDictionary<string,object> objects)
The validation method can then read these dictionary objects and use it accordingly.

Some code example:

The Validation Method is written like this...




public static void ValidateDataFields(BusinessObject businessObject,IDictionary<string,object> objects)
                var currentCaptionSet = (CaptionSet)objects["CurrentCaptionSet"];
                if (currentCaptionSet == null) throw new Exception("Validate method called with incorrect parameters");



The validation is called like this ...


var supportObjects = new Dictionary<string, object> {{"CurrentCaptionSet", frontEndContext.CaptionSet}};

var validationResult = businessObjectToUpdate.Validate(supportObjects);





If someone is interested in the code, see the Source code section.