title: WebApi, Autofac, System.Web.Http.Filters.ActionFilterAttribute Instance Per Request
body: <p>We have been using Autofac in our application (MVC 4 now) for a long time, we have dozens of attributes on the base controller everything inherits from and it has all been working fine so when the request begins our service is created and then available through all the attributes and on the controller action.</p>
  
  <p>We are now looking at WebApi and have created our WebApi controller and created an attribute on the base controller using the ActionFilterAttribute from the HTTP namespace.  However the problem starts here where the service injected on the property on the attribute is not the same instance as that on the ApiController.  Looking at the link below this seems to be known <a href="http://www.strathweb.com/2012/11/asp-net-web-api-and-dependencies-in-request-scope/">ASP.NET Web API and dependencies in request scope</a>    </p>
  
  <p>However the solution here is not ideal as we don't want our controllers to know about the dependency injection, we just want to use the service we are injecting to the property and know it is one instance per request.</p>
  
  <p>We are calling this:</p>
  
  <pre><code>  builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
  </code></pre>
  
  <p>And</p>
  
  <pre><code>  GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
  </code></pre>
  
  <p>Our classes are currently registered with Autofac as InstancePerLifetimeScope, what we want is to be able to have per request working for MvcControllers and ApiControllers.</p>
  
  <p>Is that possible?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>So basically this line returns the right service for the request (i.e. the same instance that is also on the ApiController)</p>
  
  <pre><code>var service = actionContext.Request.GetDependencyScope().GetService(typeof(IOurService);
  </code></pre>
  
  <p>But the property injection instance on the ActionFilterAttribute is not the same and if I change the Autofac registration to be InstancePerApiRequest I get the following error:</p>
  
  <p>"No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself."</p>