My web app solution consists of 3 projects:
- Web App (ASP.NET MVC)
- Business Logic Layer (Class Library)
- Database Layer (Entity Framework)
I want to use Ninject to manage the lifetime of the DataContext generated by the Entity Framework in the Database Layer.
The Business Logic layer consists of classes which reference repositories (located in the database layer) and my ASP.NET MVC app references the business logic layer’s service classes to run code. Each repository creates an instance of the MyDataContext object from the Entity Framework
Repository
public class MyRepository
{
private MyDataContext db;
public MyRepository
{
this.db = new MyDataContext();
}
// methods
}
Business Logic Classes
public class BizLogicClass
{
private MyRepository repos;
public MyRepository
{
this.repos = new MyRepository();
}
// do stuff with the repos
}
Will Ninject handle the lifetime of MyDataContext despite the lengthy dependency chain from the Web App to the Data Layer?
EDIT
I has some problems with it some time ago, but now it seems to work:
Instead of using HttpModule, you can use OnePerRequestBehavior and it will take care of handling context in current request.
EDIT 2
OnePerRequestBehavior needs to be registered in web.config, because it depends on HttpModule too:
In IIS6:
With IIS7:
PREVIOUS ANSWER
It is your responsibility to dispose context when it is not needed. Most popular way in ASP.NET is to have one ObjectContext per request. I do it by having HttpModule:
This is injection rule:
My Repository takes ObjectContext in constructor: