開發環境: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 { public static void Register() { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetCallingAssembly())//注冊mvc的Controller .PropertiesAutowired();//屬性注入 //1、無接口類注入 //builder.RegisterType<BLL.newsClassBLL>().AsSelf().InstancePerRequest().PropertiesAutowired(); //2、有接口類注入 //注入BLL,UI中使用 builder.RegisterAssemblyTypes(typeof(BLL.BaseBLL<>).Assembly) .AsImplementedInterfaces() //是以接口方式進行注入 .InstancePerRequest() //每次http請求 .PropertiesAutowired(); //屬性注入 //注入DAL,BLL層中使用 builder.RegisterAssemblyTypes(typeof(DAL.BaseDAL<>).Assembly).AsImplementedInterfaces() .InstancePerRequest().PropertiesAutowired(); //屬性注入 //Cache的注入,使用單例模式 //builder.RegisterType<RedisCacheManager>() // .As<ICacheManager>() // .SingleInstance() // .PropertiesAutowired(); //移除原本的mvc的容器,使用AutoFac的容器,將MVC的控制器對象實例交由autofac來創建 var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
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();
//autofac屬性注入 public InewsClassBLL bll { get; set; }
[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