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. "
c # asp.net-mvc asp.net-web-api autofac
user351711
source share