Can someone explain to me how and why do we need to use Dispose()? It’s part of the default controller template that comes with ASP.NET MVC 4. Shouldn’t the garbage collector in .NET automatically kick in when the object, in this case data from a database is no longer in use?
Is it correct that Dispose() should be used when loading from a database but not regular object assignments?
Disposeis used (the Disposable pattern, so to speak) when dealing with unmanaged resources. Yes, the .NET Garbage Collector will clean up .NET managed objects, but database connections are lower level objects not managed by the .NET Framework. Same thing with file handlers — use the Dispose pattern when you open/write to files as the actual file handle is not managed by .NET.The MSDN documentation describes
IDisposableand why you’d implement it.EF uses it because underneath the
DbContextis aDbDataConnection, which works with unmanaged resources. In those situations, it is best to implementIDisposableand handle the clean up of your unmanaged resources accordingly.