title: Using Unity Framework & Validation Application Block to Validate Method Parameters
body: <h2>Question</h2>
  
  <p>Is it posible to have the <code>Validation.Validate()</code> method of the Validation Application Block see each parameter of the <code>IParameterCollection</code> supplied by Unity as my custom <code>UserModel</code>?</p>
  
  <hr>
  
  <h2>Background:</h2>
  
  <p>I am attempting to use both Unity and the Validation Application Block to validate method parameters.  </p>
  
  <p>I would like to be able to denote a method as <code>[RequiresValidation()]</code> and the parameters of that method with the appropriate validation attributes.</p>
  
  <p>So, something like this:</p>
  
  <pre><code>[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; }
  }
  </code></pre>
  
  <p>I have created a custom HandlerAttribute that will initiate the call to the validation handler as shown.</p>
  
  <pre><code>public class RequiresValidationAttribute : HandlerAttribute
  {
    public override ICallHandler CreateHandler(IUnityContainer container)
    {
      return new ValidationCallHandler();
    }
  }
  </code></pre>
  
  <p>Now, the Validation Handler will attempt to validate each parameter of the method:</p>
  
  <pre><code>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;
  
        // ...
      }
  
      // ...
    }
  }
  </code></pre>
  
  <h2>Problem</h2>
  
  <p>The <code>Validation.Validate()</code> method will always return <strong>true</strong>.  Based on my observations, it seems the validation logic is treating the <code>parameter</code> as an <code>object</code> and not my <code>UserModel</code>.</p>
  
  <hr>
  
  <h2>Question</h2>
  
  <p>Is it posible to have the <code>Validation.Validate()</code> method of the Validation Application Block see each parameter of the <code>IParameterCollection</code> supplied by Unity as my custom <code>UserModel</code>?</p>