How Dispose works with Entity Framework

Can someone explain to me how and why we need to use Dispose ()? This is part of the default controller template that comes with ASP.NET MVC 4. Should the garbage collector in .NET automatically fire when an object, in which case the data from the database is no longer used?

Is it correct that Dispose () should be used when loading from a database, but not into regular object assignments?

+2
source share
2 answers

Dispose used (the so-called one-time pattern) when working with unmanaged resources. Yes, the .NET garbage collector will clear managed .NET objects, but database connections are lower-level objects that are not managed by the .NET Framework. The same with file handlers - use the Dispose pattern when opening / writing to files, since the actual file descriptor is not controlled by .NET.

The MSDN documentation describes IDisposable and why you implement it.

EF uses it because under DbContext there is a DbDataConnection that works with unmanaged resources. In such situations, it is best to implement IDisposable and process your unmanaged resources accordingly.

+2
source

Garbage collection works automatically on any managed memory resources. However, sometimes there are classes that use unmanaged memory or special resources without memory, such as file descriptors that need to be freed.

Entity Framework contexts access connections from a common connection pool and need to be informed when they can refuse these connections because they will no longer be used.

Is it correct that Dispose () should be used when loading from a database, but not into regular object assignments?

The Dispose method should only be implemented by classes that can use unmanaged memory or non-memory resources. If a class implements the IDisposable interface, you should always call it Dispose when you are done with this object.

+1
source

All Articles