在该篇博文中,我们将应用Autofac,以依赖注入的方式建立传统ASP.NET页面与服务/中间层之间的联系,建立“呈现”与“控制”的纽带。

  那么,如何将依赖注入(Dependency Injection)植入ASP.NET中呢?

  ASP.NET页面生命周期的整个过程均被ASP.NET工作者进程把持,这也就基本上切断了我们想在这个过程中通过“构造函数注入(Constructor injection)”的方式植入服务/中间层的念头,并且要求我们必须在进入页面生命周期之前完成这个植入的过程。基于这种考虑,我们可以采用IhttpModule基础之上“属性注入(Property injection)”方式。以下为实现细节: www.liuhebao.com

  1、 引用相应dll

  向ASP.NET应用程序添加以下引用:

  Autofac.dll

  Autofac.Integration.Web.dll

  2、 构造随Application一同启动的ContainerProvider属性

  在进入页面生命周期之前植入,我们选择在Global类中实现。使Global类实现Autofac.Integration.Web命名空间下的IcontainerProviderAccessor接口。该接口公开了一名为ContainerProvider的属性,其为服务的消费者(在此处即为ASP.NET页面)提供根容器。该属性应在应用程序启动的时候构建完成,也就是在Application_Start事件中完成。具体构建代码如下: www.yzyedu.com

// 构建应用容器并注册依赖
var builder = new ContainerBuilder();
builder.Register<EmpMng>().As<IEmpMng>().HttpRequestScoped();
// ... 注册其他依赖 ... 
// 注册完成后,便可设置ContainerProvider属性
_containerProvider = new ContainerProvider(builder.Build());

  3、 设置web.config

  基于IhttpModule的原理,便需在web.config中设置相关的内容。

<configuration> 
  <system.web> 
    <httpModules> 
      <!--IIS6下设置 --> 
      <add 
        name="ContainerDisposal" 
        type="Autofac.Integration.Web.ContainerDisposalModule,
                                               Autofac.Integration.Web"/> 
      <add 
        name="PropertyInjection" 
        type="Autofac.Integration.Web.Forms.PropertyInjectionModule,               
                                               Autofac.Integration.Web"/> 
    </httpModules> 
  </system.web> 
  <system.webServer> 
    <!--IIS7 下设置--> 
    <modules> 
      <add 
        name="ContainerDisposal" 
        type="Autofac.Integration.Web.ContainerDisposalModule,  
                                               Autofac.Integration.Web" 
        preCondition="managedHandler"/> 
      <add 
        name="PropertyInjection" 
        type="Autofac.Integration.Web.Forms.PropertyInjectionModule,  
                                               Autofac.Integration.Web" 
        preCondition="managedHandler"/> 
    </modules> 
  </system.webServer> 
</configuration>


  说明:

  ContainerDisposalModule,页面请求结束,Autofac释放之前创建的组件/服务。

  PropertyInjectionModule,在页面生命周期之前,向页面注入依赖项。

  4、 页面属性获取服务/中间层

  在.aspx页面后台放置一公开的属性,用来接收服务/中间层。

// 用来接收服务/中间层的属性
public IEmpMng SomeDependency { get; set; } 
protected void Page_Load(object sender, EventArgs e)
{
    lblEmp.Text = this.SomeDependency.selectOneEmp();
}


  以上讲解的方式仅仅粗糙的实现了ASP.NET页面与服务/中间层的连通,有很多的细节,如服务/中间层的组织方式、连通处是否可以引入Singleton模式等,均需进一步的研究。本人在IoC领域初来乍到,不足与错误之处望各位斧正!