Tutorials Design Patterns in C#
Unit of Work Pattern — Complete Guide
Unit of Work Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 25 of 69
Unit of Work Pattern
GoF Core ✓ → Enterprise → Cloud & Craft
Enterprise · 2 — App patterns · ~6 min · Module 4: Enterprise Design Patterns
What is this?
Unit of Work tracks a business transaction’s changes and commits them as one — often wrapping a DbContext transaction.
Why should you care?
ShopNest placing an order may write Order + Outbox rows that must commit together.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public interface IUnitOfWork { Task CommitAsync(); }
public sealed class OrderUnitOfWork : IUnitOfWork
{
private readonly List<Func<Task>> _work = new();
public void Register(Func<Task> action) => _work.Add(action);
public async Task CommitAsync()
{
foreach (var a in _work) await a();
Console.WriteLine("committed");
}
}
var uow = new OrderUnitOfWork();
uow.Register(() => { Console.WriteLine("insert order"); return Task.CompletedTask; });
uow.Register(() => { Console.WriteLine("insert outbox"); return Task.CompletedTask; });
await uow.CommitAsync();
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Registered actions run then commit.
- With EF, UoW usually calls SaveChangesAsync once.
- Do not hold DB transactions open across HTTP calls to payment providers.
Practice next
- Commit the sample work list.
- Map to DbContext.SaveChangesAsync in real code.
- Include outbox insert in the same commit.
- Simulate failure before commit.
- Return number of operations committed.
Remember
One business commit. Track related changes. Keep external I/O outside.
ShopNest order+outbox UoW
Place-order commits both rows atomically.
Outcome: No order without its event row.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!