Unit of Work + Repository Pattern in TypeScript

Recently in my career, I have been doing a lot study about design patterns and how they can applied to everyday software creation to achieve good software design.

What are design patterns?

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. - Source Making

There are different types of design patterns but for the scope of this article I would only be showing you how I implemented the Unit of Work pattern in TypeScript.

Unit of Work Pattern

The Unit of Work pattern is used to group one or more operations (usually database operations) into a single transaction or “unit of work”, so that all operations either pass or fail as one.

According to Martin Fowler, the unit of work pattern maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

If you are building an enterprise application using a layered architecture, you would probably have to apply the UoW pattern to structure your database operations. I personally consider managing database transactions in your service layer as a code smell.

Talk is cheap! So let me show you the code ;)

Step 1: Create your Unit of Work

Step 2: Unit of Work Factory

The purpose of the UnitOfWorkFactory is create an instance of the UoW.


  1. https://sourcemaking.com/design_patterns
  2. http://jasonwatmore.com/post/2015/01/28/unit-of-work-repository-pattern-in-mvc5-and-web-api-2-with-fluent-nhibernate-and-ninject
  3. https://martinfowler.com/eaaCatalog/unitOfWork.html
Show Comments