Generic Repository Entity Framework Part II

lanjutan dari Generic Repository Entity Framework Part I

Unit Of Work

Unit Of Work memastikan bahwa banyak repository hanya akan menshare satu database contex yang sama sehingga membuat transaksi menjadi atomic. Artinya jika satu gagal, semuanya gagal untuk menjaga konsistensi data.

Seperti biasa, kita buat interfacenya dulu.

public interface IUnitOfWork : IDisposable
     {
         IGenericRepository GetGenericRepository()
           where T : class;

         void SaveChanges();
     }

Kemudian kita membuat konkrit classnya.

public class EFUnitOfWork : IUnitOfWork
     {
         private BookStoreEntities _context = new BookStoreEntities();
         private bool _disposed;



         /// <summary>
         /// Gets the generic repository.
         /// </summary>
         /// <typeparam name="T"></typeparam>
         /// <returns></returns>
         public IGenericRepository<T> GetGenericRepository<T>() where T : class
         {
             return new EFGenericRepository<T>(_context);
         }


         /// <summary>
         /// Saves the changes.
         /// </summary>
         public void SaveChanges()
         {
             try
             {
                 _context.SaveChanges();
             }
             catch (DbEntityValidationException e)
             {
                 throw;
             }
         }

         /// <summary>
         /// Releases unmanaged and - optionally - managed resources.
         /// the dispose method is called automatically by the injector depending on the lifestyle
         /// </summary>
         /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
         protected virtual void Dispose(bool disposing)
         {
             if (!this._disposed)
             {
                 if (disposing)
                 {
                     _context.Dispose();
                 }
             }
             this._disposed = true;
         }

         public void Dispose()
         {
             Dispose(true);
             GC.SuppressFinalize(this);
         }
     }

 

Nantinya kita akan membuat instance dari Generic Repository di atas dengan melewatkan class entities sebagai paramater dan menggunakan method GetGenericRepository

public class BookBLL : IBookBLL
        {
            private readonly IUnitOfWork _unitOfWork;
            private readonly IGenericRepository _bookRepo;
            public BookBLL(IUnitOfWork unitOfWork)
            {
                _unitOfWork = unitOfWork;
                _bookRepo = _unitOfWork.GetGenericRepository();
            }

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout /  Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout /  Ubah )

Connecting to %s