title: asp.net MVC5 - Dependency Injection and AuthorizeAttribute
body: <p>I searched a long time for a solution for my problem. I have a custom AuthorizeAttribute that needs a Dependency to a "Service" that has access to a DbContext. 
  Sadly the Dependency Injection did not work in the custom AuthorizeAttribute and was always null. </p>
  
  <p>I came up with an (for me) acceptable solution. Now I want to know if my solution can cause unforeseen behaviour?</p>
  
  <p><strong>Global.asax.cs</strong></p>
  
  <pre><code> CustomAuthorizeAttribute.AuthorizeServiceFactory = () =&gt; unityContainer.Resolve&lt;AuthorizeService&gt;();
  </code></pre>
  
  <p><strong>CustomAuthorizeAttribute.cs</strong></p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
      public class CustomAuthorizeAttribute : AuthorizeAttribute
      {
          public static Func&lt;AuthorizeService&gt; AuthorizeServiceFactory { get; set; }
  
          public Privilege Privilege { get; set; }
  
          protected override bool AuthorizeCore(HttpContextBase httpContext)
          {
              bool authorized = base.AuthorizeCore(httpContext);
              if (!authorized)
              {
                  return false;
              }
  
              return AuthorizeServiceFactory().AuthorizeCore(httpContext, Privilege);
          }
      }
  </code></pre>
  
  <p><strong>AuthorizeService.cs</strong></p>
  
  <pre><code>public class AuthorizeService
  {
      [Dependency]
      public UserService UserService { private get; set; }
  
      public bool AuthorizeCore(HttpContextBase httpContext, Privilege privilege)
      {
          ApplicationUser user = UserService.FindByName(httpContext.User.Identity.Name);
          return UserService.UserHasPrivilege(user.Id, privilege.ToString());
      }
  }
  </code></pre>
  
  <p>Is this an acceptable solution? Will I run into nasty problems in the future or is there maybe a better way to use Dependency Injection in a custom AuthorizeAttribute?</p>