Recently i configured Autofac with ASP.Net MVC 4 and WebAPI. Here are the steps required to configure Autofac
- Install package Autofac.MVC4
- Install package Autofac.WebApi
- Add a class AutofacBootstrap. Use this class to configure the dependencies within your project. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public class AutofacBootstrap { internal static void Init(ContainerBuilder builder) { } } - Open Global.asax file and add a method like This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
private void RegisterIOC() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterApiControllers(typeof(MvcApplication).Assembly); AutofacBootstrap.Init(builder); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new Autofac.Integration.WebApi.AutofacWebApiDependencyResolver(container); } - Call the method from Application_Start
- And you are done !!