3
votes

I'm trying to use depedency resolver inside a Web Api method. This worked fine and works fine with classic ASP.NET MVC with the DepedencyResolver.GetService()

But I can't get this to work inside WepApi methods.

My registration register all instances as InstancePerApiRequest and if I add any of all the types I have registred in my bootstrapper on the constructor of my WebAPiConroller thay inject fine but not anymore when calling them inside.

Like this in my say Get Method

var userRepository = (IUserRepositoryu)GlobalConfiguration
       .Configuration.DependencyResolver.GetService(typeof(IUserRepository));

I got the no scope WebRequest error. The strange thing is that it worked fine in Beta before they change it all to the GlobalConfiguration.

So my question is, how can I activate my Autofac registered assemblies in the lifetime scope of my webAPi as before?

My error:

"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 reqested 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."

 var resolver = new AutofacWebApiDependencyResolver(container);
 configuration.DependencyResolver = resolver;
3

3 Answers

5
votes

In Web API the global dependency resolver is used to access global instances. Per-request services come from a dependency scope that Web API creates to handle the request. I'm not sure that there is any way in Web API to access the current dependency scope - it would be interesting to know.

The best option here is to just use dependency injection rather than calling the resolver directly like this. Which part of your code needs to make this call?

0
votes

AutoFac has integration with ASP.NET WebAPI consider to use it.

Also dependecy resolver for WebAPi is slightly different to ASP.NET MVC, so make shure, that you have implemented resolver suitable for WebAPI and added it to WebAPI configuration.

http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver

0
votes

As the error indicated, you must always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime. The correct way is getting the dependency from current web api request:

// Get the request lifetime scope so you can resolve services.
var requestScope = Request.GetDependencyScope();
// Resolve the service you want to use.
var userRepository = requestScope.GetService(typeof(IUserRepository)) as IUserRepository;

See more from Autofac offical documentations: http://docs.autofac.org/en/latest/integration/webapi.html#standard-web-api-filter-attributes-are-singletons