简体   繁体   中英

How does Dispose work with Entity Framework

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?

Garbage collection works automatically on any managed memory resources. However, sometimes there are classes that use unmanaged memory or special non-memory resources like file handles that need to be released.

Entity Framework contexts get access to connections from a shared connection pool, and need to be told when they can relinquish those connections because they are no longer going to be used.

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

The Dispose method should only be implemented by classes that may use unmanaged memory or non-memory resources. If a class does implement the IDisposable interface, you should always call Dispose on it when you're finished with that object.

Dispose is 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 IDisposable and why you'd implement it.

EF uses it because underneath the DbContext is a DbDataConnection , which works with unmanaged resources. In those situations, it is best to implement IDisposable and handle the clean up of your unmanaged resources accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM