Is it possible to configure Autofac to work with ASP.NET MVC and ASP.NET Web Api

It is certainly possible to configure Autofac to work with both MVC and Web API. This is expected to be a very common scenario. There are two separate dependency resolver implementations because MVC and Web API can be used independently of one another. The same applies for the Autofac integrations.

When using both MVC and Web API in the same application each will require its own dependency resolver, though they can be provided with the same instance of the container.

var builder = new ContainerBuilder();

// Add your registrations

var container = builder.Build();

// Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

// Set the dependency resolver for MVC.
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);

It is also possible to share registrations between the two because the InstancePerApiRequest and InstancePerHttpRequest lifetime scopes now share the same tag.

Note that the mechanism for setting the dependency resolver for Web API and MVC is different. Web API uses GlobalConfiguration.Configuration.DependencyResolver and MVC uses DependencyResolver.SetResolver.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)