Question
Is it posible to have the Validation.Validate()
method of the Validation Application Block see each parameter of the IParameterCollection
supplied by Unity as my custom UserModel
?
Background:
I am attempting to use both Unity and the Validation Application Block to validate method parameters.
I would like to be able to denote a method as [RequiresValidation()]
and the parameters of that method with the appropriate validation attributes.
So, something like this:
[RequiresValidation()]
public void SaveUser(UserModel user)
{
// ...
}
public class UserModel
{
[StringLengthValidator(3, 255)]
[RegexValidator(@"^[a-zA-Z0-9]${3,255}")]
public string Name { get; set; }
[StringLengthValidator(0, 255)]
[RegexValidator(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")]
public string EMail { get; set; }
}
I have created a custom HandlerAttribute that will initiate the call to the validation handler as shown.
public class RequiresValidationAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new ValidationCallHandler();
}
}
Now, the Validation Handler will attempt to validate each parameter of the method:
public class ValidationCallHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
// Validate the method parameters
ValidateArguments(input.Arguments);
// Call the method that was intercepted
return getNext()(input, getNext);
}
private static void ValidateArguments(IParameterCollection parameterCollection)
{
foreach (var parameter in parameterCollection)
{
var results = Validation.Validate(parameter);
if (results.IsValid) continue;
// ...
}
// ...
}
}
Problem
The Validation.Validate()
method will always return true. Based on my observations, it seems the validation logic is treating the parameter
as an object
and not my UserModel
.
Question
Is it posible to have the Validation.Validate()
method of the Validation Application Block see each parameter of the IParameterCollection
supplied by Unity as my custom UserModel
?