依赖注入容器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(); 

posted @ 2016-11-23 17:53  在西天取经的路上……  阅读(273)  评论(0编辑  收藏  举报