when and how should i call IDisposable Interface? asp.net MVC 3
i was just googling it and could find anything开发者_StackOverflow that give me a good example of how to implement and what are the best scenarios when i should call the IDisposable interface
please if someone could post the example and the explain it that would be a great help and could give me a good start..
thanks in advance..
Your controllers that use EF should include a dispose method
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
See Ensuring that Database Connections Are Not Left Open
When you use the MVC scaffolding, it creates the dispose method for you. See also Controller.Dispose Method (Boolean)
The ASP.NET MVC framework calls Dispose when the request has completed processing. Developers typically do not have to call Dispose. If you derive a class from Controller and the derived class uses unmanaged memory, managed operating-system resources (such as files), or COM objects, you should implement Dispose to clean up these resources. You should also call the Dispose method of the base class. The Dispose method leaves the Controller instance in an unusable state. After you call Dispose, you must release all references to the Controller instance so that the garbage collector can reclaim the memory that the Controller instance was occupying.
For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.
The IDisposable
interface is meant to be used by classes that also access un-managed resources. This gives the class a chance to clean up those un-managed resources as soon as possible.
The MSDN Page for the IDisposable
Interface actually provides a good example as to what this means.
Since you tagged MVC Ill reply specific to mvc controllers. If you aren't using any resources you need to dispose (ie resources that support a Dispose method and you aren't disposing then already in a code method) then you should implement IDisposable and call dispose in your objects there. It's quite rare you need to do this though and generally will see it if using an ObjectContext or DbContext entity framework class in your controller. However I prefer creating and disposing any objects in the same method.
Note however the discussion here where its mentioned to essentially keep this responsibility of the caller implementing IDisposable (ie your controller implementing it) to a dependency injection framework calling the dispose for you automatically.
Ensuring IDisposable call on objects created in the controller and handed off to view
精彩评论