ASP.Net Wep.API and ASP.NET MVC uses two different IDependencyResolver
(because they designed the Wep.API to not depend on ASP.NET MVC) so you need to setup both:
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(container);
So the AutofacDependencyResolver
is needed to inject decencies to regular MVC Controller
derived controllers.
And the AutofacWebApiDependencyResolver
is needed to inject dependencies to the Web.API ApiController
derived controllers.
And don’t forget to register your Api controllers in your container builder with the call (it differs from usual builder.RegisterControllers
method):
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());