Asp.Net MVC三層架構之autofac使用教程

開發環境:vs201五、.net4.5.二、mvc五、ef6css

Autofac簡介

IOC控制反轉(Inversion of Control,縮寫爲IOC),Autofac是一個開源的依賴注入框架,Autofac是asp.net中比較經常使用的IOC容器之一web

IOC的目標是消除代碼中的new(實例化)語句,把實例化類的控制權轉移到別的地方,這個地方一般會在一個程序加載時只執行一次的全局方法中,達到解耦的目的。api

DI依賴注入(Dependency Injection,縮寫爲DI),組件之間依賴關係由容器在運行期決定,形象的說,即由容器動態的將某個依賴關係注入到組件之中。依賴注入的目的並不是爲軟件系統帶來更多功能,而是爲了提高組件重用的頻率,併爲系統搭建一個靈活、可擴展的平臺。經過依賴注入機制,咱們只須要經過簡單的配置,而無需任何代碼就可指定目標須要的資源,完成自身的業務邏輯,而不須要關心具體的資源來自何處,由誰實現。架構

三層架構

Autofac安裝

經過Nuget安裝Autofac和Autofac.Mvc5mvc

Autofac配置

一、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層asp.net

二、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使用

使用構造函數注入ui

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能夠隨意變更spa

end

屬性注入方法https://www.jianshu.com/p/f5d6346b0a7b

相關文章
相關標籤/搜索