WebApi, Autofac, System.Web.Http.Filters.ActionFilterAttribute Instance Per Request

We have been using Autofac in our application (MVC 4 now) for a long time, we have dozens of attributes on the base controller, on which everything is inherited, and everything works fine, so when the request starts, our service is created and then accessible through all the attributes and controller action.

Now we look at WebApi and created our WebApi controller and created the attribute on the base controller using the ActionFilterAttribute from the HTTP namespace. However, the problem starts here when the service entered in the attribute property is not the same instance as on ApiController. Looking at the link below, as you know, ASP.NET web API and query dependencies

However, the solution here is not ideal, since we do not want our controllers to know about dependency injection, we just want to use the service that we enter in the property, and we know that this is one instance for the request.

We invoke this:

builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); 

and

  GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); 

Our classes are currently registered in Autofac as InstancePerLifetimeScope, we want each request to work on MvcControllers and ApiControllers.

Is it possible?

EDIT:

So basically this line returns the correct service for the request (i.e. the same instance that is also on ApiController)

 var service = actionContext.Request.GetDependencyScope().GetService(typeof(IOurService); 

But the instance of the property injection in the ActionFilterAttribute is not the same, and if I change the Autofac registration to InstancePerApiRequest, I get the following error:

β€œNo tag area corresponding toβ€œ AutofacWebRequest ”is visible from the area in which the instance was requested. This usually indicates that the component registered as an HTTP request is requested by the SingleInstance () component (or a similar scenario.) As part of web integration DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime dependencies are always requested, never from the container itself. "

+8
c # asp.net-mvc asp.net-web-api autofac
source share
1 answer

This is a known issue and a design issue in the Web API. When filter instances are first created in the web API, they are cached, so Autofac should allow the implementation of properties using the root lifecycle scope, rather than the scope of the request. Autofac does not have the ability to inject any properties - filters are effectively single-point in the web API, and there is no way to change this.

After that, if you need on-demand services in your filter, you should use the GetDependencyScope() trick.

See Autofac for more on this:

+10
source

All Articles