在asp.net mvc控制器中使用Autofac來解析依賴
如下Controller中使用構造函數依賴注入接口IPeople
:
public class AutoFacController : Controller { public IPeople _people; public AutoFacController(IPeople people) { _people = people; } // GET: AutoFac public ActionResult Index() { ViewBag.test = _people.Getpeople(); return View(); } }
如何使用AutoFac如下:
1、在App_Start創建類文件AutofacConfig.cs
引用
using Autofac; using Autofac.Integration.Mvc;
以下為逐個注冊方法:
//創建autofac管理注冊類的容器實例 var builder = new ContainerBuilder(); //下面就需要為這個容器注冊它可以管理的類型 //builder的Register方法可以通過多種方式注冊類型,之前在控制台程序里面也演示了好幾種方式了。 builder.RegisterType<People>().As<IPeople>(); //builder.RegisterType<DefaultController>().InstancePerDependency(); //使用Autofac提供的RegisterControllers擴展方法來對程序集中所有的Controller一次性的完成注冊 builder.RegisterControllers(Assembly.GetExecutingAssembly()); //生成具體的實例 var container = builder.Build(); //下面就是使用MVC的擴展 更改了MVC中的注入方式. DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
以下為批量注冊方法:
public class AutofacConfig { /// <summary> /// 負責調用autofac框架實現業務邏輯層和數據倉儲層程序集中的類型對象的創建 /// 負責創建MVC控制器類的對象(調用控制器中的有參構造函數),接管DefaultControllerFactory的工作 /// </summary> public static void Register() { //實例化一個autofac的創建容器 var builder = new ContainerBuilder(); //告訴Autofac框架,將來要創建的控制器類存放在哪個程序集 (Wchl.CRM.WebUI) Assembly controllerAss = Assembly.Load("Wchl.WMBlog.WebUI"); builder.RegisterControllers(controllerAss); //告訴autofac框架注冊數據倉儲層所在程序集中的所有類的對象實例 Assembly respAss = Assembly.Load("Wchl.WMBlog.Repository"); //創建respAss中的所有類的instance以此類的實現接口存儲 builder.RegisterTypes(respAss.GetTypes()).AsImplementedInterfaces(); //告訴autofac框架注冊業務邏輯層所在程序集中的所有類的對象實例 Assembly serpAss = Assembly.Load("Wchl.WMBlog.Services"); //創建serAss中的所有類的instance以此類的實現接口存儲 builder.RegisterTypes(serpAss.GetTypes()).AsImplementedInterfaces(); // builder.RegisterType<>().As<>(); //創建一個Autofac的容器 var container = builder.Build(); //將MVC的控制器對象實例 交由autofac來創建 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } }
2、在全局Global.asax類Application_Start()方法中調用AutofacConfig配置類方法
protected void Application_Start(object sender, EventArgs e) { AutofacConfig.Register(); }
3、Web Api配置Autofac方法
引用
using Autofac.Integration.WebApi;
參考資料:http://docs.autofac.org/en/latest/integration/webapi.html
var builder = new ContainerBuilder(); // Get your HttpConfiguration. var config = GlobalConfiguration.Configuration; // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // OPTIONAL: Register the Autofac filter provider. builder.RegisterWebApiFilterProvider(config); // Set the dependency resolver to be Autofac. var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
