依赖注入到达多远?

Oma*_*mar 5 asp.net-mvc dependency-injection ninject

我的Web应用程序解决方案包含3个项目:

  1. Web应用程序(ASP.NET MVC)
  2. 业务逻辑层(类库)
  3. 数据库层(实体框架)

我想用Ninject来管理的生命周期DataContext由产生Entity FrameworkDatabase Layer.

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

知识库

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

     // methods
}
Run Code Online (Sandbox Code Playgroud)

业务逻辑类

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

     // do stuff with the repos
}
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*Led 3

编辑

前段时间我遇到了一些问题,但现在它似乎可以工作:

Bind<CamelTrapEntities>().To<CamelTrapEntities>().Using<OnePerRequestBehavior>();
Run Code Online (Sandbox Code Playgroud)

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

编辑2

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

在 IIS6 中:

<system.web>
  <httpModules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
  </httpModules>
</system.web> 
Run Code Online (Sandbox Code Playgroud)

使用 IIS7:

<system.webServer> 
  <modules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
  </modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

之前的回答

您有责任在不需要时处理上下文。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();            
    }
}
Run Code Online (Sandbox Code Playgroud)

这是注入规则:

Bind<CamelTrapEntities>().ToMethod(c => (CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]);
Run Code Online (Sandbox Code Playgroud)

我的存储库在构造函数中采用 ObjectContext:

public Repository(CamelTrapEntities ctx)
{
    _ctx = ctx;
}
Run Code Online (Sandbox Code Playgroud)