Why does no one disposes DbContext after WebApi controller operation?

后端 未结 6 2506
梦谈多话
梦谈多话 2021-02-19 20:32

I am aware of various tutorials as well as complete examples targeting WebApi & Entity Framework (even from Microsoft) that have WebApi

6条回答
  •  囚心锁ツ
    2021-02-19 20:43

    Personally, whenever I see the type implements IDisposable, I'm almost certain that I'm going to use a using statement when working with new instances of this type.

    When the variable goes out of scope (like in your case with the context variable going out of scope when the execution returns from GetInternet method), its memory is eventually going to be reclaimed by garbage collector but this doesn't mean that any native handlers (e.g. file handlers or database connections) are going to be closed which can have a very serious negative impact on your application.

    So, consider always wrapping an IDisposable into the using construct:

    using (var context = new InternetDbContext())
    {
      // Your code goes here
    }
    

    Hope this helps.

提交回复
热议问题