title: How to rewrite code to use IAuthorizationFilter with dependency injection instead of AuthorizeAttribute with service location in Asp Net Web Api?
body: <p>I have the custom <code>AuthorizeAttribute</code> where I need to use one of the business layer services to validate some data in the database before giving user a permission to view the resource. In order to be able to allocate this service within the my <code>AuthorizeAttribute</code> I decided to use service location "anti-pattern", this is the code:</p>
  
  <pre><code>internal class AuthorizeGetGroupByIdAttribute : AuthorizeAttribute
  {
      private readonly IUserGroupService _userGroupService;
  
      public AuthorizeGetGroupByIdAttribute()
      {
          _userGroupService = ServiceLocator.Instance.Resolve&lt;IUserGroupService&gt;();
      }
  
      //In this method I'm validating whether the user is a member of a group. 
      //If they are not they won't get a permission to view the resource, which is decorated with this attribute.
      protected override bool IsAuthorized(HttpActionContext actionContext)
      {
          Dictionary&lt;string, string&gt; parameters = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x =&gt; x.Key, x =&gt; x.Value);
          int groupId = int.Parse(parameters["groupId"]);
          int currentUserId = HttpContext.Current.User.Identity.GetUserId();
  
          return _userGroupService.IsUserInGroup(currentUserId, groupId);
      }
  
      protected override void HandleUnauthorizedRequest(HttpActionContext actionContex)
      {
          if (!HttpContext.Current.User.Identity.IsAuthenticated)
          {
              base.HandleUnauthorizedRequest(actionContex);
          }
          else
          {
              actionContex.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
          }
      }
  }
  </code></pre>
  
  <p>I have couple of other attributes like this in my application. Using service locator is probably not a good approach. After searching the web a little bit I found some people suggesting to use <code>IAuthorizationFilter</code> with dependency injection instead. But I don't know how to write this kind of <code>IAuthorizationFilter</code>. Can you help me writing <code>IAuthorizationFilter</code> that will do the same thing that the <code>AuthorizeAttribute</code> above?</p>