简体   繁体   中英

.NET Disposing DBContext on Controllers Dispose action

I want to know if I am right doing this kind of job?

Here is a simple example.

public class HomeController : Controller
{
    MYDBContext db = new MYDBContext();

    public ActionResult Index()
    {
        //do some thing with db here
        return View("~/Views/Home/Index.cshtml");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

So, I'm creating a db object at the top of the controller. and disposing it when controller is disposing?

I'm wondering if there is a memory leak because of unclosed DB connections?

Edit : This is a MVC project.

As far as db connection concern .NET maintains a pool of connections for every connection string you use in your application, for perfomance reasons (because opening and closing connections often might be costly in terms of perfomance). That pool has certain minimum and maximum size (controlled by MinPoolSize and MaxPoolSize connection string parameters). When you open a connection (via SqlConnection.Open) - it might be taken out of the pool and not really opened afresh. When you close connection (which is also done by disposing EF context) - connection might be put into the pool instead, and not really closed. When connection is idle for certain time it might be removed from the pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM