Unit of Work Design Pattern in .NET

RyseSoft
3 min readAug 4, 2022

Hello, I am Tolga Şükrü Özkan. I am a 3rd year student at Ankara Yıldırım Beyazıt University, Department of Computer Engineering. I am doing my internship at RyseSoft company. In this article, I will try to explain the use of Unit of Work in .NET.

Hello,

In this article, we’ll look at the Unit of Work Design Pattern, a business design pattern that enables us to execute database operations in bulk and permits complete recovery in the event of a potential error.

What is the Unit of Work Design Pattern?

The Unit Of Work design pattern is a design pattern that prevents every database-related action in our software application from being immediately reflected to the database. Instead, it accumulates all actions and makes sure they are completed all at once over a single connection, reducing database costs.

Any insert, update, or delete request performed to the database using the Ado.NET database architecture or any ORM tool (such as Entity Framework) used with the.NET framework is automatically carried out in a transaction. As a result, processing each request will be exceedingly expensive. Because the transaction mechanism can track all database activity, it has the ability to reverse any transactions that were conducted in accordance with our predetermined conditions in the event of a malfunction, mistake, or procedure. Therefore, the transaction treats the invoice as a significant cost as it will not carry out this duty for free. Additionally, if we take into account the fact that a unique transaction is initiated for each query, our cost double and the database becomes highly taxing.

Unit of Work in .NET

First of all, The Unit of Work generally used with the Repository Pattern. So, you should add Repository Pattern in your project. Then you can use

Then We should use Interface for clean code like this:

Let’s implement this interface in UnitOfWork class:

Now you can use this unit of work pattern in your services. Let’s see how unit of work is used in services.

Finally, let’s take a look at how this service used in actions in the controller side.

How does the unit of work work?

A design pattern called Unit Of Work runs batch database operations one at a time, stating how many records were impacted by this batch operation. Unit of Work, which is typically used in conjunction with the Repository Design Pattern, may (typically) control all query operations from a single center when utilized in this way.

All of our requests are submitted to the database simultaneously as a result of the Unit Of Work design pattern, and they are all handled by the transaction we manually start. As a result, there is a significant decrease in cost and an indirect boost in performance.

Hope to see you in my next articles…

Author:Tolga Şükrü Özkan

Linkedln:https://www.linkedin.com/in/tolgasozkan/

Github:https://github.com/tolgaozkann

--

--