I am aware of various tutorials as well as complete examples targeting WebApi
& Entity Framework
(even from Microsoft) that have WebApi
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 DbContext
that 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.