依賴注入容器Autofac與MVC集成


Autofac是應用於.Net平台的依賴注入(DI,Dependency Injection)容器,具有貼近、契合C#語言的特點。隨着應用系統的日益龐大與復雜,使用Autofac容器來管理組件之間的關系可以“扁平化”錯綜復雜的類依賴,具有很好的適應性和便捷度。
  在該篇博文中,我們將應用Autofac,以依賴注入的方式建立傳統ASP.NET頁面與服務/中間層之間的聯系,建立“呈現”與“控制”的紐帶。

  那么,如何將依賴注入(Dependency Injection)植入ASP.NET中呢?
  ASP.NET頁面生命周期的整個過程均被ASP.NET工作者進程把持,這也就基本上切斷了我們想在這個過程中通過“構造函數注入(Constructor injection)”的方式植入服務/中間層的念頭,並且要求我們必須在進入頁面生命周期之前完成這個植入的過程。基於這種考慮,我們可以采用IhttpModule基礎之上“屬性注入(Property injection)”方式。以下為實現細節:
  1、 引用相應dll
     

      下載Autofac,注意你下載的版本是否與你項目的.net版本一致

     


  向ASP.NET應用程序添加以下引用:
  Autofac.dll
  Autofac.Integration.Web.dll
     Autofac.Integration.Web.Mvc.dll


  2、 設置web.config
  接下來要修改web.config文件,新建一個HTTP模塊,由於控制反轉容器會動態初始化對象,所以該模塊的目的就是適當的將建立的對象釋放。
<configuration>
<system.web>
<httpModules>
<!--IIS6下設置 --> 

<httpModules>
      <add name= " ContainerDisposal " type= " Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web " />
    </httpModules> 
</system.web> 
<system.webServer> 


 

<!--IIS7 下設置-->

 <system.webServer>
    <modules>
      <add name= " ContainerDisposal " type= " Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web " />
    </modules>
    <validation validateIntegratedModeConfiguration= " false " />
  </system.webServer>



  說明:
  ContainerDisposalModule,頁面請求結束,Autofac釋放之前創建的組件/服務。
  PropertyInjectionModule,在頁面生命周期之前,向頁面注入依賴項。

     3、修改Global.asax頁面內容,在Application_Start事件里啟用控制反轉容器,讓.net MVC能夠與autofac集成

    

     由於使用autofac必須用到一些命名空間,必須添加以下引用

 

      using System.Reflection;
      using Autofac;
      using Autofac.Integration.Web;
      using Autofac.Integration.Web.Mvc;

 

     在MvcApplication類中設定IContainerProviderAccessor接口,並在類別層級添加以下代碼

     

      static IContainerProvider _containerProvider;

       public IContainerProvider ContainerProvider
{
get {  return _containerProvider; }

 

     在Application_Start方法中的最前面添加以下代碼:

     

  var builder =  new ContainerBuilder();

            SetupResolveRules(builder);

            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            _containerProvider =  new ContainerProvider(builder.Build());

            ControllerBuilder.Current.SetControllerFactory( new AutofacControllerFactory(_containerProvider));

 

    


  4、 頁面屬性獲取服務/中間層

  在.aspx頁面后台放置一公開的屬性,用來接收服務/中間層。

// 用來接收服務/中間層的屬性
public IEmpMng SomeDependency { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
lblEmp.Text = this.SomeDependency.selectOneEmp();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM