Last active
August 29, 2015 14:26
-
-
Save haydosw/78557261775163150716 to your computer and use it in GitHub Desktop.
Fluent Validator Engine - Helper class to find all validators and provide a common way of validating objects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Helper class to find all validators and provide a common way of validating objects. | |
/// </summary> | |
public class ValidationEngine | |
{ | |
private static readonly Dictionary<Type, IValidator> AllValidatorsInAssembly; | |
static ValidationEngine() | |
{ | |
AllValidatorsInAssembly = new Dictionary<Type, IValidator>(); | |
FindAndInstantiateAllAbstractValidators(); | |
} | |
private static void FindAndInstantiateAllAbstractValidators() | |
{ | |
// https://stackoverflow.com/questions/8645430/get-all-types-implementing-specific-open-generic-type | |
foreach (var abstractValidator in from x in Assembly.GetAssembly(typeof(ValidationEngine)).GetTypes() | |
let y = x.BaseType | |
where !x.IsAbstract && !x.IsInterface && | |
y != null && y.IsGenericType && | |
y.GetGenericTypeDefinition() == typeof(AbstractValidator<>) | |
select x) | |
{ | |
// No need to safeguard this - if we get null's fail hard | |
var typeOfValidator = abstractValidator.BaseType.GenericTypeArguments.First().UnderlyingSystemType; | |
// https://stackoverflow.com/questions/731452/create-instance-of-generic-type | |
var validator = (IValidator)Activator.CreateInstance(abstractValidator); | |
AllValidatorsInAssembly.Add(typeOfValidator, validator); | |
} | |
} | |
/// <summary> | |
/// Will look at all registered abstract validators | |
/// Find the validator matching the given type of item | |
/// Run validate method to determine if item is valid | |
/// </summary> | |
/// <typeparam name="T">Not Needed - Type will be inferred</typeparam> | |
/// <param name="item">Item for validation</param> | |
/// <returns>ValidationResult</returns> | |
public static ValidationResult Validate<T>(T item) | |
{ | |
var classRequiringValidation = typeof(T); | |
if (AllValidatorsInAssembly.ContainsKey(classRequiringValidation) == false) | |
throw new Exception($"Unable to locate validator {classRequiringValidation.FullName} - " + | |
$"Please create a new AbstractValidator<{classRequiringValidation.FullName}>"); | |
return AllValidatorsInAssembly[classRequiringValidation].Validate(item); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment