Does a new() EF Context in the constructor of a controller properly handle the disposal?

亡梦爱人 提交于 2019-12-23 05:13:42

问题


ASP.NET website recommends implementing Disposable on my repository which affects my datacontext.

Is it sufficient for me to initialize the datacontext here, and casually let ASP.NET dispose of the resources?

Under what conditions will it not get called? I am debugging frequently (ending the debug session mid page) and noticed that I needed to reboot to reclaim some memory.


回答1:


MVC will not dispose any IDisposable instances you create. You are in-charge of disposing them. You can either over ride Dispose method of the controller.

public class MyController : Controller
{

      protected override void Dispose(bool disposing) 
      {
          //dispose them here
      }
}

Or use a Dependency Injection/IoC framework to control the lifetime of the IDisposable instances. Many DI/IoC frameworks will automatically call the Dispose method if the framework created those instances.



来源:https://stackoverflow.com/questions/8192172/does-a-new-ef-context-in-the-constructor-of-a-controller-properly-handle-the-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!