I have a controller that instantiates a database context for EF. (As I’m sure most that aren’t implementing the repository pattern do.)
When I ran code analysis on my project it recommended implementing IDisposable so I wrote the following code.
#region Implementation of IDisposable
public void Dispose()
{
Console.WriteLine("Dispose");
Dispose(true);
GC.SuppressFinalize(this);
}
// The bulk of the clean-up code is implemented in Dispose(bool)
protected override void Dispose(bool disposing)
{
Console.WriteLine("Dispose(disposing)");
if (disposing)
{
// free managed resources
if (_dataService != null)
{
((IDisposable)_dataService).Dispose();
_dataService = null;
}
// free managed resources
if (_db != null)
{
((IDisposable)_db).Dispose();
_db = null;
}
}
base.Dispose(disposing);
}
#endregion
I’ve also tried doing.
protected new virtual void Dispose(bool disposing)
But my console.writeline statements never execute. What am I doing wrong? Why isn’t Dispose() being called on my controller?
you don’t do anything wrong. You get the recommentation because you hold some fields in your class (cotnroller) that implements IDisposable. The framework will call the “overload”-version so just move all your code in there.
Details on MSDN
BTW you won’t see the console-writeline – use System.Diagnostic.Debug.WriteLine instead