开发者

Disposing bound object in Ninject

开发者 https://www.devze.com 2023-03-22 14:46 出处:网络
I am binding an object of class DonorContext (which derives from DbContext of EntityFramework) as below in Global.ascx as below.

I am binding an object of class DonorContext (which derives from DbContext of EntityFramework) as below in Global.ascx as below.

kernel.Bind<DonorContext>().ToSelf().InRequestScope().OnDeactivation(DisposeDonorContext);

I was expecting that at end of request, Ninject will call the DisposeDonorContext method. But it never gets called.

What I could gather from web was that the objects of IDisposible types will automatically get their Dispose method called when they go out of scope. This is not happening in my case and hence I was trying the OnDeactivation() to dispose the DonorContext (which doesn't happen either).

Any ideas why the dispose 开发者_如何学JAVAis not happening?


Ninject will automatically call the Dispose method of objects implementing IDisposable (at least that's what happened when I tested it with the latest version). If this doesn't happen for you I suspect that the problem is that you never use this DonorContext anywhere in your application. So it never gets instantiated and never gets disposed. For example if you had a controller which takes this context as constructor argument:

public class HomeController: Controller
{
    private readonly DonorContext _context;
    public HomeController(DonorContext context)
    {
        _context = context;
    }

    public ActionResult Index()
    {
        return View();
    }
}

It should work. It would also work if you had a service layer that takes this context as constructor argument and then you use this service in the controller (with constructor injection). At the end of the day you must have a controller which takes some dependency which itself might be the DonorContext or some other dependency which itself depends on DonorContext (repository, service, ...) in order to trigger the dependency injection chain.

This being said working with a concrete type such as DonorContext in your controller kind of defeats the purpose of using Dependency Injection as you are hardcoding it.

0

精彩评论

暂无评论...
验证码 换一张
取 消