依赖注入到达多远?

时间:2010-03-14 01:12:40

标签: asp.net-mvc dependency-injection ninject

我的网络应用解决方案包含3个项目:

  1. Web App(ASP.NET MVC)
  2. 业务逻辑层(类库)
  3. 数据库层(实体框架)
  4. 我想使用Ninject来管理DataContextEntity Framework生成的Database Layer的生命周期。

    业务逻辑层由引用存储库(位于数据库层)的类组成,我的ASP.NET MVC应用程序引用业务逻辑层的服务类来运行代码。每个存储库都从实体框架

    创建MyDataContext对象的实例

    存储库

    public class MyRepository
    {
         private MyDataContext db;
         public MyRepository
         {
            this.db = new MyDataContext();
         }
    
         // methods
    }
    

    业务逻辑类

    public class BizLogicClass
    {
         private MyRepository repos;
         public MyRepository
         {
              this.repos = new MyRepository();
         }
    
         // do stuff with the repos
    }
    

    尽管从Web App到数据层的冗长依赖链,Ninject会处理MyDataContext的生命周期吗?

2 个答案:

答案 0 :(得分:3)

修改

前段时间我遇到了一些问题,但现在似乎有用了:

Bind<CamelTrapEntities>().To<CamelTrapEntities>().Using<OnePerRequestBehavior>();

您可以使用OnePerRequestBehavior而不是使用HttpModule,它将负责处理当前请求中的上下文。

编辑2

OnePerRequestBehavior需要在web.config中注册,因为它也依赖于HttpModule:

在IIS6中:

<system.web>
  <httpModules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
  </httpModules>
</system.web> 

使用IIS7:

<system.webServer> 
  <modules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
  </modules>
</system.webServer>

以前的答案

您有责任在不需要时处理上下文。 ASP.NET中最流行的方法是每个请求都有一个ObjectContext。我是通过HttpModule来实现的:

public class CamelTrapEntitiesHttpModule : IHttpModule
{
    public void Init(HttpApplication application)
    {
        application.BeginRequest += ApplicationBeginRequest;
        application.EndRequest += ApplicationEndRequest;
    }

    private void ApplicationEndRequest(object sender, EventArgs e)
    {
        ((CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]).Dispose();
    }

    private static void ApplicationBeginRequest(Object source, EventArgs e)
    {
        HttpContext.Current.Items[@"CamelTrapEntities"] = new CamelTrapEntities();            
    }
}

这是注射规则:

Bind<CamelTrapEntities>().ToMethod(c => (CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]);

My Repository在构造函数中使用ObjectContext:

public Repository(CamelTrapEntities ctx)
{
    _ctx = ctx;
}

答案 1 :(得分:3)

只想提一下Autofac with the ASP.Net integration内置请求生命周期支持。解析RequestContainer中的实例,并在请求结束时处理它们(如果实现IDisposable)。

你应该让你的课程DI友好:

public class MyRepository
{
     private MyDataContext db;
     public MyRepository(MyDataContext context)
     {
        this.db = context;
     }

     // methods
}

public class BizLogicClass
{
     private MyRepository repos;
     public BizLogicClass(MyRepository repository)
     {
          this.repos = repository;
     }

     // do stuff with the repos
}