Reputation: 188
I have the following extension method:
public static SessionUserInfo ToSessionUserInfo(this Customer customer)
{
//Some logic here which need some services
}
I'm using autofac with web api and owin, but because this is an extension method i cannot use Constructor injection. So i need to resolve the services from the logic in the code.
Normally using MVC and Autofac.Integration.MVC I would do something like that:
var scope = AutofacDependencyResolver.Current.RequestLifetimeScope;
MyService service = scope.Resolve<MyService>();
But I could not find a way to accomplish the same with Web API.
How can I do this in Web Api?
Upvotes: 0
Views: 2551
Reputation: 1309
Unless you are using OWIN in your API, you should have your Autofac configuration setup in your WebAPI like this, which is the standard way to configure Autofac for WebApi.
Include nuget pacakge Autofac.Integration.WebApi
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<MyType>();
var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
Should you need to request the LifetimeScope like in your example, you can then request this from GlobalConfiguration.
var scope = GlobalConfiguration.Configuration.DependencyResolver.GetRequestLifetimeScope();
MyService service = scope.Resolve<MyService>();
Autofac WebApi configuration reference
Upvotes: 1