Why does no one disposes DbContext after WebApi controller operation?

后端 未结 6 2504
梦谈多话
梦谈多话 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:56

    You should call Dispose() or use using when working with DbContext but you don't have to.

    If you want to play safe, always wrap in a using or Dispose() but if you want to have a better understanding of EF DbContext implementation, keep reading.

    Long story short, EF usually knows when is the time to Close a connection, so in the majority of the cases, call or not call Dispose() does the same result and doesn't have any impact in memory usage or performance because garbage collector will handle properly, unlike most of the IDisposable classes.

    But, there are two main reasons that you should wrap in using or call Dispose() specifically for EF DbContext.

    First is when someone manually open a connection with ObjectContext from the DbContext, if you don't call Dispose()/using you could leave open connections as those connections will not be managed automatically by EF.

    The second reason is that the derived class of DbContextthat you are instantiating could be overriting the default behavior of dispose for example to aggregate the disposal of other unmanaged resources into the lifetime of the context, so if not properly disposed, it'll leave those resources alive.

    This article is a must read.

提交回复
热议问题