How to remove DbContext (or object) in asp.net mvc3 App when Ninject is used as dependency converter

For this demo, I created a fake database repository + below

Fake db + repository

public interface IDemoRepository { string[] GetUsers(); } public class DemoRepository : IDemoRepository, IDisposable { public string[] GetUsers() { string[] Users = { "Robert","Linda","Jack"}; return Users; } public void Dispose() { //do nothing throw new Exception("Disposed is called"); } } 

My controller looks like this:

  public class TestController:Controller { protected IDemoRepository _repository; public BaseController(IDemoRepository repository) { _repository = repository; } public ActionResult() { var users = _repository.GetUsers(); Return View(users); } } 

Non-injection part

I installed ninject from NUGet and added below code to allow repositories

 kernel.Bind<IDemoRepository>().To<DemoRepository>() 

Ninject does not call DemoRepository.Dispose , I added a breakpoint, even my current code throws an error, but Ninject does not call DemoRepository.Dispose .

Can any body suggest me how to remove an object.

+4
source share
2 answers

Make sure your repository is associated with the request scope in Ninject if you want it to be deleted:

 kernel.Bind<IDemoRepository>().To<DemoRepository>().InRequestScope(); 
+5
source

You do not need Dispose() of you DbContext , since it already correctly manages all connections. Here is a quote from ASP.NET MVC Tip # 34 - Dispose of your DataContext (or Dont) :

The most important consequence of calling the DataContext.Dispose () method is that any open connections associated with the DataContext are closed. It may seem really important, but it is not. The reason is that it doesn't matter that the DataContext class already manages its connections. By default, the DataContext class opens and closes the connection automatically.

...

Most often, when you call the Dispose () method of a DataContext object, any database connection associated with the DataContext object is already closed. The DataContext object closed the database connection immediately after executing the database request. So the Dispose () method really has nothing to do.

+1
source

All Articles