title: How to implement Dispose pattern in MVC Repository pattern architecture
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Anyway, here is the code.</p>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>    protected override void Dispose(bool disposing)
      {
          _myService.Dispose();
  
          // Call base class implementation
          base.Dispose(disposing);
      }
  </code></pre>
  
  <p><strong>Service</strong></p>
  
  <pre><code>    public void Dispose()
      {
          _myRepository.Dispose();
      }
  </code></pre>
  
  <p><strong>Domain</strong></p>
  
  <pre><code>public interface IMyRepository : IDisposable
  </code></pre>
  
  <p><strong>Repository</strong></p>
  
  <p>Extra question: Is the IDisposable required here?</p>
  
  <pre><code>    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);
      }
  </code></pre>
  
  <p>I have put together (below) what I believe is correct, but not entirely sure.</p>
  
  <p><strong>Question. Will the above code cleanup all unmanaged resources, e.g. database connections? (i.e. is what I've done correct)</strong></p>