title: Dependency-Injected Validation in Web API
body: <p>In MVC, I can create a Model Validator which can take Dependencies.  I normally use FluentValidation for this.  This allows me to, for example, check on account registration that an e-mail address hasn't been used (NB: This is a simplified example!):</p>
  
  <pre><code>public class RegisterModelValidator : AbstractValidator&lt;RegisterModel&gt; {
      private readonly MyContext _context;
      public RegisterModelValidator(MyContext context) {
          _context = context;
      }
      public override ValidationResult Validate(ValidationContext&lt;RegisterModel&gt; context) {
          var result = base.Validate(context);
          if (context.Accounts.Any(acc =&gt; acc.Email == context.InstanceToValidate.Email)){
              result.Errors.Add(new ValidationFailure("Email", "Email has been used"));
          }
          return result;
      }
  }
  </code></pre>
  
  <p>No such integration exists for Web API with FluentValidation.  There have been a <a href="https://stackoverflow.com/a/13045097/163495">couple</a> of <a href="https://fluentvalidation.codeplex.com/SourceControl/network/forks/paulduran/webapisupportv2/contribution/3940" rel="nofollow noreferrer">attempts</a> at this, but neither have tackled the Dependency Injection aspect and only work with static validators. </p>
  
  <p>The reason this is difficult is due to the different in implementation of ModelValidatorProvider and ModelValidator between MVC and Web API.  In MVC, these are instantiated per-request (hence injecting a context is easy).  In Web API, they are static, and the ModelValidatorProvider maintains a cache of ModelValidators per type, to avoid unnecessary reflection lookups on every request.</p>
  
  <p>I've been trying to add the necessary integration myself, but have been <a href="https://stackoverflow.com/q/15026349/163495">stuck trying to obtain the Dependency Scope</a>.  Instead, I thought I'd step back and ask if there any other solutions to the problem - if anyone has come up with a solution to performing Model Validation where dependencies can be injected.</p>
  
  <p>I do NOT want to perform the validation within the Controller (I am using a <a href="https://stackoverflow.com/a/11724405/163495">ValidationActionFilter</a> to keep this separate), which means I can't get any help from the constructor injection of the controller. </p>