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

后端 未结 2 762
猫巷女王i
猫巷女王i 2021-02-06 15:23

For this Demo I have created a fake Database+repository as below

Fake Db + Repository

 public interface IDemoRepository
    {
        string[] GetUser         


        
相关标签:
2条回答
  • 2021-02-06 15:58

    Make sure that your repository is bound to the request scope in Ninject if you want it to be disposed:

    kernel.Bind<IDemoRepository>().To<DemoRepository>().InRequestScope();
    
    0 讨论(0)
  • 2021-02-06 15:58

    You don't need to Dispose() of you DbContext, since it already manages all connections properly itself. Here's a quote from ASP.NET MVC Tip #34 – Dispose of Your DataContext (or Don’t):

    The most important consequence of calling the DataContext.Dispose() method is that any open connections associated with the DataContext get closed. This might seem really important, but it’s not. The reason that it is not important is that the DataContext class already manages its connections. By default, the DataContext class opens and closes a connection automatically.

    ...

    Most often, when you call the Dispose() method on the DataContext object, any database connection associated with the DataContext object is already closed. The DataContext object has closed the database connection right after executing the database query. So, the Dispose() method really doesn't have anything to do.

    0 讨论(0)
提交回复
热议问题