I use this first approach to validate a set of entities before submitting them to the database. The Validation.Validate method is completely skipped, because it is only able to handle a single specific type. For this reason I use the ValidationFactory.CreateValidator
for each object in a collection of specified objects. This is especially useful when using O/RM frameworks, such as LINQ to SQL and Entity Framework (you can read
here how I exactly do this).
I looked at the source for the 4.1 ObjectCollectionValidator and this first approach will fail in certain situations when the ObjectCollectionValidator is used. Take for instance the scenario where we define a type Customer and a derived type PreferredCustomer
and a type PreferredCustomerGroup, containing a collection of PreferredCustomers. All validations are configured using a configuration file and Customer validations are not duplicated for PreferredCustomer. The configuration also holds the ObjectCollectionValidator
for the PreferredCustomers property on PreferredCustomerGroup. The property uses the following configuration: <validator type="ObjectCollectionValidator" targetType="PreferredCustomer" />.
With this setup, validating a PreferredCustomer directly with my Validate(IEnumerable<object> entities) will be successful, because the method will iterate the PreferredCustomer's base types to get the all validations. However, when we validate the
PreferredCustomerGroup entity, the validation could yield invalid results, because the ObjectCollectionValidator will simply get a single validator using the ValidationFactory.CreateValidator(this.targetType, this.targetRuleSet) method. The ObjectCollectionValidator
(of course) doesn't walk the type hierarchy and the Customer validations are not triggered. The PreferredCustomers on PreferredCustomerGroup may seem valid, while in fact they could be invalid.
While I'm not sure about the ObjectCollectionValidator in VAB 5.0, I expect it to behave the same.
With the second approach, I build a custom IConfigurationSource and supply it to the overload of ValidationFactory.CreateValidator that takes an IConfigurationSource as you correctly guessed.
I start to believe that this approach will both for version 4.1 and 5.0 be the only approach that will yield correct results (besides of course, manually duplicating validations for derived types in the config file).
If you find an easier workaround, please let me know. I will do the same.