Reading up alot on how to implement the Dispose pattern in a typical layered MVC architecture, I have come across alot of answers and even contradictions, which has now confused me.
I'm using the Domain Model pattern, and Repository pattern. Note, not using UoW, or Dependency Injection. I may use DI soon (not sure yet), which means the architecture would change and the Dispose technique also.
Anyway, here is the code.
Controller
protected override void Dispose(bool disposing)
{
_myService.Dispose();
// Call base class implementation
base.Dispose(disposing);
}
Service
public void Dispose()
{
_myRepository.Dispose();
}
Domain
public interface IMyRepository : IDisposable
Repository
Extra question: Is the IDisposable required here?
public class MyRepository : IMyRepository, IDisposable
// Flag, has Dispose already been called?
private bool disposed = false;
// Protected implementation of Dispose pattern
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
// Free any other managed objects here
_context.Dispose();
}
}
// Free any unmanaged objects here
this.disposed = true;
}
// Public implementation of Dispose pattern callable by consumers
public void Dispose()
{
// Dispose of unmanaged resources
Dispose(true);
// Suppress finalization
GC.SuppressFinalize(this);
}
I have put together (below) what I believe is correct, but not entirely sure.
Question. Will the above code cleanup all unmanaged resources, e.g. database connections? (i.e. is what I've done correct)