2010-03-14 106 views
5

我的web应用程序的解决方案包括3个项目:依赖注入有多远?

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

我想使用Ninject管理Database LayerEntity Framework生成的DataContext的生存期。

业务逻辑层由引用存储库(位于数据库层中)的类组成,我的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 
} 

威尔Ninject处理的MyDataContext寿命尽管从Web冗长的依赖链应用程序到数据层?

回答

3

编辑

我有前一段时间一些问题,但现在它似乎工作:

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

而不是使用HTTP模块,你可以使用OnePerRequestBehavior,它会照顾处理当前请求中的上下文。

EDIT 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"]); 

我的仓库发生的ObjectContext中构造函数:

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

是什么“似乎工作”是什么意思? – jfar 2010-03-14 02:46:07

+0

@jfar:我在几分钟前检查并调用kernel.Get <>两次给了我请求中的同一个实例。我不记得之前有什么问题,但不知何故,我决定不使用它。与此同时,我下载了新的消息来源,但直到今天才进行检查,所以它得到了正确的修正。 – LukLed 2010-03-14 02:54:00

3

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

你应该让你的班迪友好,但:

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 
}