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?
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:
Ninject.Mvc3
NuGet packageHave 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();
}
}
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>();
}
Run the application. As expected at the end of the request, the FooDbContext
instance is disposed and the NotImplementedException
exception is thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With