開發環境:vs2015、.net4.5.2、mvc5、ef6
Autofac簡介
IOC控制反轉(Inversion of Control,縮寫爲IOC),Autofac是一個開源的依賴注入框架,Autofac是asp.net中比較常用的IOC容器之一
IOC的目標是消除代碼中的new(實例化)語句,把實例化類的控制權轉移到別的地方,這個地方通常會在一個程序加載時只執行一次的全局方法中,達到解耦的目的。
DI依賴注入(Dependency Injection,縮寫爲DI),組件之間依賴關係由容器在運行期決定,形象的說,即由容器動態的將某個依賴關係注入到組件之中。依賴注入的目的並非爲軟件系統帶來更多功能,而是爲了提升組件重用的頻率,併爲系統搭建一個靈活、可擴展的平臺。通過依賴注入機制,我們只需要通過簡單的配置,而無需任何代碼就可指定目標需要的資源,完成自身的業務邏輯,而不需要關心具體的資源來自何處,由誰實現。
三層架構
Autofac安裝
通過Nuget安裝Autofac和Autofac.Mvc5
Autofac配置
1、App_Start文件夾裏新建AutoFacConfig.cs
using System; using System.Reflection; using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; namespace cms.Web { public class AutoFacConfig { /// <summary> /// 負責調用autofac框架實現業務邏輯層和數據倉儲層程序集中的類型對象的創建 /// 負責創建MVC控制器類的對象(調用控制器中的有參構造函數),接管DefaultControllerFactory的工作 /// </summary> public static void Register() { //實例化一個autofac的創建容器 var builder = new ContainerBuilder(); //告訴Autofac框架,將來要創建的控制器類存放在哪個程序集 (UI),從當前運行的bin目錄下加載程序集 Assembly controllerAss = Assembly.Load("cms.Web"); builder.RegisterControllers(controllerAss); //告訴autofac框架註冊數據倉儲層所在程序集中的所有類的對象實例 Assembly respAss = Assembly.Load("cms.DAL"); //以接口形式保存被創建類的對象實例 builder.RegisterTypes(respAss.GetTypes()).AsImplementedInterfaces(); //告訴autofac框架註冊業務邏輯層所在程序集中的所有類的對象實例 Assembly serpAss = Assembly.Load("cms.BLL"); //以接口形式保存被創建類的對象實例 builder.RegisterTypes(serpAss.GetTypes()).AsImplementedInterfaces(); //創建一個Autofac的容器 var container = builder.Build(); //移除原本的mvc的容器,使用AutoFac的容器,將MVC的控制器對象實例交由autofac來創建 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
注意:UI層需要引用dal和bll層
2、Global.asax配置Autofac
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); BundleTable.EnableOptimizations = true;//js、css壓縮 MiniProfilerEF6.Initialize();//MiniProfiler監控ef GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();//webapi默認JSON AutoFacConfig.Register();//autofac:控制反轉,依賴注入配置 }
Autofac使用
使用構造函數注入
using System; using System.Web.Mvc; using cms.Model; using cms.IBLL; //using cms.BLL; //不需要應用bll,但需要引用IBLL namespace cms.Web.Areas.Admin.Controllers { public class NewsController : BaseController { //未使用Autofac前直接實例化的寫法 //public newsBLL bll = new newsBLL(); public InewsBLL bll { get; set; } public NewsController(InewsBLL _ibll) { bll = _ibll; } [HttpPost] [ValidateAntiForgeryToken] [ValidateInput(false)] public ActionResult Add(news vmodel,FormCollection forms) { news model = new news(); model.title = Request["title"]; model.times = DateTime.Now; model = bll.Add(model); if (model.ID > 0) { return RedirectToAction("list"); } ViewData["mess"] = "添加失敗"; return View(vmodel); } public ActionResult Edit(int id) { news model = bll.Find(id); return View(model); } // GET: Admin/Admins/Delete/5 public ActionResult Delete(int id) { if (bll.Delete(id)) { return Redirect(Request.UrlReferrer.ToString()); } else { Common.JSHelper.AlertRedirect("操作失敗", Request.UrlReferrer.ToString()); } return RedirectToAction("list"); } } }
//ui層不再依賴於BLL,只依賴於IBLL,BLL可以隨意變動
end