Step 4: Solution with Unit of Work pattern

by sunil ravulapalli /5. July 2013 23:18 /software-design /Comments (0)

Add IGenericRepository the Core project

public interface IGenericRepository<T> where T : class
{ 
   void Insert(T entity); IEnumerable<T> GetAll();
}

Add IUnitOfWork to the Core project

public interface IUnitOfWork : IDisposable
{ 
   IGenericRepository<WishListItem> WishListItemRepository { get; } 
   void Save();
}

Add GenericRepository to the Data project

public class GenericRepository<T> : IGenericRepository<T> where T : class 
{ 
  readonly CompanyDbContext _context; 
  readonly DbSet<T> _dbSet; 
  public GenericRepository(CompanyDbContext context) 
  {  
     _context = context;  
     _dbSet = context.Set<T>(); 
  } 
  public void Insert(T entity) 
  { 
      _dbSet.Add(entity); 
  } 
  public IEnumerable<T> GetAll() 
  {  
     return _dbSet.AsEnumerable(); 
  }
}

Add UnitOfWork to the Data project

public class UnitOfWork : IUnitOfWork
{ 
   readonly CompanyDbContext _context; 
   public UnitOfWork() 
   {  
     _context = new CompanyDbContext(); 
   } 
   private bool _disposed; 
   protected virtual void Dispose(bool disposing) 
   {  
       if (!_disposed)  
      {   
          if (disposing)   
          {    
              _context.Dispose();   
          }  
      }  
      _disposed = true; 
    } 
    public void Dispose() 
    {  
      Dispose(true);  
      GC.SuppressFinalize(this); 
     }       
     public void Save() 
     {  
        _context.SaveChanges(); 
      } 
      public IGenericRepository<WishListItem> WishListItemRepository 
      {  
          get { return new GenericRepository<WishListItem>(_context); } 
      }
}

You can find the solution on GitHub.

https://github.com/sunilrav/Wishlist.4.SolutionWithUnitOfWork.git

blog comments powered by Disqus