Before starting to explain how to implement a Unit of Work (Uow) pattern using a real and practical case, it is important to clarify that there are several ways to implement a UoW. Some are more purist or manual forms, while others are simpler.
All comments on other forms of implementation are of course welcome.
Issue Summary
Let’s suppose that our User Story states the following: “As a Sales System, when selling a product using the system, I would like to; inform the Stock Control System, inform the Distribution System, and inform (by means of a notification) the Selling User and the Buying User”
It seems quite simple: a user buys a product from an online store, the stock must be reduced, the process for sending the product purchased must be initiated, and the owner of the product and the user who is buying it must be informed that the transaction has been completed (via e-mail or something similar).
The problem that presents itself here is when we want to be transactional: what do we do if there is an error in the distribution system? Do we sell the product anyway? Do we report the bug and move on?
in the order
Solution: Use a Unit Of Work
What are we going to need?
- A dictionary or key-value map where we will store each step executed correctly (so in the event that we need to rollback we simply execute the opposite operation at each step)
- Adapters to connect to each of the third party systems
- A repository to store the data from our operation (the sale of the product)
And of course a piece of code
Project structure
Code details
a) Adapters: Adapters allow us to define the signatures that must respect our adaptations of the external services that we will be using (please read more about this if you have any doubts).



In the interface a few methods are proposed just as an example, but the idea is to define the methods that we need in our UoW that we can mock up.

2. Unit Of Work: The code for a UoW is not complex since it consists of the steps defined in the user case. What is important is knowing how to handle exceptions and how to react to them. It is also important that there is some way to rollback all dependencies.




As you can see in the code, the implementation has two private methods “Commit” and “Rollback”. These two methods will be responsible for executing the necessary operations so that the Unit Of Work remains consistent.

About the Author
Mauricio Bergallo is a Systems Engineer with extensive knowledge in a variety of programming languages. Great experience and understanding with all aspects of the software development life cycle.