Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject + ASP.net MVC + Entity Framework - when is my context disposed?

I am using Ninject in my MVC 3 application and one of my dependencies is on Entity Framework:

interface IFooRepository
{
    Foo GetFoo(int id);
}

public EFFooRepository : IFooRepository
{
    private FooDbContext context;

    public EFFooRepository(FooDbContext context)
    {
        this.context = context;
    }
 }

I set up a binding like so in Ninject, so if I have more than one dependency and they both need a data context they end up sharing the same context:

Bind<FooDbContext>().ToSelf().InRequestScope();

I am uncertain of when my context will be disposed. Since I am not the one that instantiates it, will it ever get disposed of or will it just get disposed of when it is garbage collected? Does Ninject know to Dispose of anything when it is done with it?

like image 783
Dismissile Avatar asked Sep 16 '11 20:09

Dismissile


1 Answers

If the FooDbContext implements IDisposable, Ninject will automatically call the Dispose method on it at the end of the request.

Here's how you can verify it:

  1. Create a new ASP.NET MVC 3 application using the default template
  2. Install the Ninject.Mvc3 NuGet package
  3. Have the following:

    public interface IFooRepository
    {
    }
    
    public class FooDbContext: IDisposable
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
    
    public class EFFooRepository : IFooRepository
    {
        private FooDbContext _context;
    
        public EFFooRepository(FooDbContext context)
        {
            _context = context;
        }
     }
    
    public class HomeController : Controller
    {
        private readonly IFooRepository _repo;
    
        public HomeController(IFooRepository repo)
        {
            _repo = repo;
        }
    
        public ActionResult Index()
        {
            return View();
        }
    }
    
  4. Add the following in the RegisterServices method of ~/App_Start/NinjectMVC3.cs:

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<FooDbContext>().ToSelf().InRequestScope();
        kernel.Bind<IFooRepository>().To<EFFooRepository>();
    }
    
  5. Run the application. As expected at the end of the request, the FooDbContext instance is disposed and the NotImplementedException exception is thrown.

like image 101
Darin Dimitrov Avatar answered Oct 19 '22 10:10

Darin Dimitrov