Tutorials Clean Architecture & DDD Mastery

Unit of Work: Ensuring atomic transactions

On this page

Atomic Integrity

The Unit of Work pattern coordinates the work of multiple repositories by creating a single database transaction that covers all of them.

1. All or Nothing

If your business process involves creating a User AND generating an Invoice AND sending an SMS, you want them all to succeed or all to fail. The Unit of Work ensures that you don't end up with a "Ghost User" who has no invoice because the second database call failed.

2. Implementation with EF Core

EF Core's `DbContext` is actually a built-in Unit of Work. When you call await context.SaveChangesAsync(), it wraps all pending changes in a single transaction. In Clean Architecture, we often wrap this in an IUnitOfWork interface to keep our shared persistence logic consistent across the whole application.

3. Architect Insight

Q: "Should the Application Service call SaveChanges?"

Architect Answer: "YES. The Application Service (the Use Case) is the coordinator of the transaction. It should call the repositories to do the work and then call UnitOfWork.CommitAsync() at the very end. This ensures that the 'Use Case' boundary and the 'Database Transaction' boundary are one and the same."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Clean Architecture & DDD Mastery
Course syllabus
1. Architectural Patterns
2. Domain-Driven Design (DDD) Foundations
3. Advanced DDD Patterns
4. Implementing the Clean Layers
5. Patterns for Data & Logic
6. Enterprise Domain Challenges
7. Testing Clean Architecture
8. Real-World Case Study
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details