Unit of Work for ASP.NET Core

Part 3: Add transaction support for repositories

Why Unit of Work?

transfer(from A, to B, amount 10) {
A = A - 10
B = B + 10
}
BookRepository.Insert(gambler);
AuthorRepository.Insert(fyodor);
Unit Of Work

Add Unit of Work

Repositories/

Refactor Generic Repository

public void Insert(T entity) {
if (entity == null) throw new ArgumentNullException("entity");
entities.Add(entity);
// Removed → context.SaveChanges();
}

Usage of Unit of Work

ConfigureService →
services.AddScoped<IUnitOfWork, UnitOfWork>();
Controllers/
try
{
_unitOfWork.BookRepository.Insert(gambler);
_unitOfWork.AuthorRepository.Insert(fyodor);
_unitOfWork.Commit();
}
catch (Exception ex)
{
_unitOfWork.Rollback();
}
   _unitOfWork.BookRepository.Insert(gambler);
throw new Exception();
_unitOfWork.AuthorRepository.Insert(fyodor);
git clone https://github.com/udarabibile/aspnetcore-webapi.git
cd aspnetcore-webapi
git checkout unit-of-work
dotnet restore
dotnet run (or dotnet watch run)

Full Stack Developer | BiBi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store