title: Entity Framework, UnitofWork pattern with dispose method
body: <p>A sample of uow:</p>
  
  <pre><code>using System;
  using ContosoUniversity.Models;
  
  namespace ContosoUniversity.DAL
  {
      public class UnitOfWork : IDisposable
      {
          private SchoolContext context = new SchoolContext();
          private GenericRepository&lt;Department&gt; departmentRepository;
          private GenericRepository&lt;Course&gt; courseRepository;
  
          public GenericRepository&lt;Department&gt; DepartmentRepository
          {
              get
              {
  
                  if (this.departmentRepository == null)
                  {
                      this.departmentRepository = new GenericRepository&lt;Department&gt;(context);
                  }
                  return departmentRepository;
              }
          }
  
          public GenericRepository&lt;Course&gt; CourseRepository
          {
              get
              {
  
                  if (this.courseRepository == null)
                  {
                      this.courseRepository = new GenericRepository&lt;Course&gt;(context);
                  }
                  return courseRepository;
              }
          }
  
          public void Save()
          {
              context.SaveChanges();
          }
  
          private bool disposed = false;
  
          protected virtual void Dispose(bool disposing)
          {
              if (!this.disposed)
              {
                  if (disposing)
                  {
                      context.Dispose();
                  }
              }
              this.disposed = true;
          }
  
          public void Dispose()
          {
              Dispose(true);
              GC.SuppressFinalize(this);
          }
      }
  }
  </code></pre>
  
  <p>As you see uow includes dispose method and inside it disposes dbContex object. Why should we explicitly dispose the dbContext object. Since it is a member of uow, outside the scope it will disposed by garbace collector automaticly. So, why are we doing this manually? As an example:</p>
  
  <pre><code>using(Uow uowObject = new Uow())
  {
        //there is a dbcontext
  }
    //it will be disposed automaticly by gc
  </code></pre>