0% found this document useful (0 votes)
47 views

Repository Pattern and Unit of Work With ASP - NET Core Web API - by Yohan Malshika - Enlear Academy

The document discusses implementing the repository pattern and unit of work pattern in ASP.NET Core Web API applications. It explains what the repository pattern and unit of work are, their benefits, and provides code examples for creating a generic repository interface, implementation, database context, and unit of work class to coordinate multiple repository operations in a single database transaction.

Uploaded by

d.m.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Repository Pattern and Unit of Work With ASP - NET Core Web API - by Yohan Malshika - Enlear Academy

The document discusses implementing the repository pattern and unit of work pattern in ASP.NET Core Web API applications. It explains what the repository pattern and unit of work are, their benefits, and provides code examples for creating a generic repository interface, implementation, database context, and unit of work class to coordinate multiple repository operations in a single database transaction.

Uploaded by

d.m.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.

of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Open in app

Repository Pattern and Unit of Work with


ASP.NET Core Web API
How to Implement a Unit Of Work with Repository Pattern in ASP.NET Core Web API

Yohan Malshika · Follow


Published in Enlear Academy
7 min read · Oct 6, 2021

Listen Share More

Hello All, I plan to tell you how to implement a unit of work with the repository
pattern in ASP.NET Core today. In that case, I'll discuss,

What is the Repository Pattern?

Non-generic and Generic Repository Pattern

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 1/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

What is the Unit of Work (UoW)?

Benefits of UoW

How to implement the unit of work with repository pattern in ASP.NET Core
Web API

1. What is the Repository Pattern?


The repository pattern creates the abstraction layer between database access and
business logic. In that case, Instead of writing the entire data access logic on the
controller, it's better to write it in a different class called a repository.

I already discussed the repository pattern with basic implementation in the below
article.

Create ASP.NET Core CRUD Web API with the Repository pattern
Hi all, Hope all are doing well!. So In the last articles, I showed you
how to create CI/CD pipeline for ASP.NET Web…
malshikay.medium.com

2. Non-Generic and Generic Repository Pattern


Non-Generic Repository Pattern

All database actions related to a given entity are defined using the non-generic
repository pattern within a separate class. For Example, suppose we have two
entities (Ex-Student and Employee ). In that case, we will create two repositories for
each entity with the basic CRUD operations and other operations related to each
entity.

Generic Repository Pattern

The generic repository pattern is used to provide common database operations for
all database entities in a single class, such as CRUD operations and so on. First, I'll
show how to implement the generic repository pattern with the Example.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 2/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

3. What is the Unit of Work (UoW)?


The Unit of Work is a type of business transaction, and it will aggregate all
Repository transactions (CRUD) into a single transaction. Only one commit will be
made for all modifications. If any transaction fails to assure data integrity, it will be
rolled back. Because it does not block any data table until it commits the
modifications, the Unit of Work is commonly referred to as a lazy evaluation
transaction.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 3/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

The above code example seems to be fine. But the issue will arise when we add
another repository for another entity like this repository. For Example, if we add the
repository for the Customer entity, we have to maintain its instance of DbContext.
Then these repositories will maintain their instance of DbContext. This could lead
to problems if each DbContext has its in-memory list of updates to entity records. In
this situation, if one repository's SaveChanges fails while the other succeeds,
database inconsistency will arise. This is where the UnitOfWork concept comes into
play.

High level of UoW and Repository Pattern

Also, You can see the high-level view of the Unit of Work and Repository pattern in
the above figure.

4. Benefits of Unit Of Work (UoW)


1. Reduce the Duplicate queries and codes

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 4/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

2. Could increase the loosely couple with DI in the application

3. Easy to do unit testing or test-driven development (TDD)

4. Increase the abstraction level and maintain the business logic separately.

5. How to implement the unit of work with repository pattern in ASP.NET Core Web API
First, we need to create an ASP.NET Core Web API project. I am not explaining how
to create it here. Then run it and check the project.

Then we need to install the required packages for use to SQL server and entity
framework core. In that case, you could navigate to Nuget package manager and
then install the required packages into our solution.

Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore

Then remove the boilerplate code that has been created when creating the project
(WeatherForecast.cs, Controller/WeatherForecastController.cs) after we need to
modify the appsettings.json file to add the connection string of our database. So, It's
a small task, and it's up to you.

In here, I follow the code-first approach in EF core to create and manage our
database. In that case, we need to create a Model (Entity) class. So, first, create the
folder called Models in the root directory and then create the Employee model class
inside the Model folder as below code.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 5/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Then we need to create DbContext for our application. In that case, Create a folder
called Data in the root directory and then create DBContext class which implement
the DbContext as below code and also need to our Employee model class into
DbContext as below code.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 6/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

You can see the DbContext class with the above code. In that code, the
OnModelCreating method provides the ability for us to manage the table properties
of the tables in the database. As well, we add our Employee model class. In that
case, the DbSet property will help to create the table which adds with it by using the
EF Core.

Then we have to create our database. In that case, navigate to the package manager
console of visual studio and then use the following commands to create the
database. First, enter the add-migration to create the migration by adding the
migration snapshot and then enter update-database to create and update the
database by using the last migration snapshot.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 7/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

add-migration initialMigration
update-database

Now we created our database with our ASP.NET Core Web API project.

Now we have to implement the repository pattern. In that case, I follow the generic
repository pattern to create the repository pattern for our project. First, we need to
create a folder called services in the root directory and then create the
IGenericRepository interface inside the service folder as the following code.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 8/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

I explained the Generic repository above. Here, T is a specific class, and the
functions will depend on our requirements and preference. In this case, I added 6
functions that are commonly used on other repositories.

Now implement this IGenericRepository. Create a new class called


GenericRepository, which implements IGenericRepository inside the services folder
as following code.

This class will implement the IGenericRepository Interface. The DBContext also will
be injected here. In this approach, all operations connected to the dbContext object
are hidden within Repository Classes. However, we have not yet
committed/updated/saved the database modifications in any way. This is something

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 9/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

that should not be done in a Repository Class. We'll discuss that with the Unit of
Work.

Now we have to create an interface called IEmployeeRepository.

Here, We need to inherit IGenericRepository and add the new functions related to
IEmployeeRepository. For Example, we could add the functions called
GetEmployeeAttendance() because it's not a common operation that is not suitable
for the IGenericRepository.

Now we have to implement this IEmployeeRepository. Create a class called


UserRepository inside the services folder as the following code.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 10/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

In here, We implement the Employee Repository by inhering the


IGenericRepository and IEmployeeRespository. In that case, we could override
functions that do not implement the database logic with the Generic Repository and
then could add the operations for that functions as above code.

Now we have to implement the Unit of Work in our project. Basically, I explained
what unit of work in the above section is. Now we have to learn it with the Example.

In that case, I create the Configuration folder in the root directory of the project
folder. Then we need to create the IUnitOfWork interface inside the configuration
folder as following code.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 11/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Now we have built one repository with the Generic Repository pattern. We could
inject the repositories that we implement in our project and then could access the
data. But when we have a lot of repositories, we need to inject all of them. It's not
good practice. In that case, we could use the unit of work to wrap all the repositories
into a single object.

The Unit of Work is in control of exposing the relevant Repositories and Committing
Changes to the DataSource in order to ensure a complete transaction with no data
loss.

Now we have to implement this interface. In that case, create UnitOfWork class
inside the configuration folder as the following code.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 12/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

We are injecting the DBContext and ILogger and implementing the CompleteAsync
and the Dispose functions to use when the commit/update/remove operations with
the database were.

Now navigate to startup class and need to register IUnitOfWork interface in our
project as follows.

// Adding the Unit of work to the DI container

services.AddScoped<IUnitOfWork, UnitOfWork>();

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 13/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

We have only to register IUnitOfWork. We don't need to register other repositories


as we are doing in the basic repository pattern. Because we inject all of the
repositories in the IUnitOfWork, then we could access them through it.

Then we have to implement the controller in our project. In that case, We have to
create the controller called EmployeeController inside the Controllers folder, as
below code.

We inject the IUnitOfWork as the object in this controller. Then we have to use the
unit of work to add the services and logic to the related methods in this controller.

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 14/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Now we have to run this project. And then we could access our ASP.NET Core Web
API as below figure.

Run the Web API project

So, We run our web API project successfully and If you need the project that we
implement, you could get it with this GitHub Repository.

We discuss some points such as Repository pattern, Non-Generic and Generic


repository pattern, Unit Of Work and its benefits, and how to implement a unit of
work with the repository pattern in the ASP.NET Core Web API project to get the
basic idea about it with this article.

So That's it for today. I hope you learned something new from my article.

See you again soon with another article !!

Learn More

OTP Login with .NET Core for Mobile-Friendly Web Apps

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 15/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

When we build web applications, implementing authentication plays


a vital role in providing personalized and secure…
enlear.academy

Integrate CK Editor to ASP .NET Core MVC Web Application


How to Use CK Editor with ASP.NET Core MVC
enlear.academy

Microsoft Azure Blob Storage with Identity UI


Using Microsoft Azure Blob Storage & ASP .NET Core MVC Web
Application with Identity UI
enlear.academy

Aspnetcore Unitofwork Repository Pattern Net Core Dotnet

Follow

Written by Yohan Malshika


501 Followers · Writer for Enlear Academy

Software Engineer @ Aizenit

More from Yohan Malshika and Enlear Academy

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 16/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Yohan Malshika in Enlear Academy

Null Handling Techniques in C#


7 Null Handling techniques that you should know in C#

4 min read · Mar 14

190 4

Niemvuilaptrinh in Enlear Academy

29 footer examples for website


https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 17/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Welcome back to my blog. Today we are going to learn Footer snippet by combining HTML,
CSS, Javascript and Bootstrap . Come on, let’s find…

5 min read · Dec 29, 2021

109 1

Niemvuilaptrinh in Enlear Academy

Best 31 Login Form Templates For Website


Free Login Form Templates

5 min read · Sep 28, 2021

143

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 18/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Yohan Malshika in Enlear Academy

Building a Dynamic Logical Expression Builder in C#


Understanding How to use And and Or Operators with Expression Trees

6 min read · May 12

119

See all from Yohan Malshika

See all from Enlear Academy

Recommended from Medium

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 19/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Itzhak

C# and .net Core Data Validation Layer


We might have a web API that accepts an HTTP POST request with a JSON payload containing
user information. We want to validate the payload…

5 min read · Feb 21

Edin Šahbaz

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 20/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Getting Started with Clean Architecture in .NET Core


4 min read · Jun 24

10 1

Lists

Staff Picks
395 stories · 215 saves

Stories to Help You Level-Up at Work


19 stories · 170 saves

Self-Improvement 101
20 stories · 403 saves

Productivity 101
20 stories · 410 saves

Matt Bentley in Better Programming

Domain-Driven Design: A Walkthrough of Building an Aggregate


A guided tour through the process of building an aggregate and some hints and tips to keep
you on the straight and narrow

9 min read · Sep 29, 2022

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 21/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

591 2

Belarmino Silva

Reduce your memory consumption to less than 50% with Entity


Framework Core
Entity Framework Core (EF Core) is an Object-Relational Mapper (O/RM) tool that enables
access and manipulation of data in different…

4 min read · Jul 3

114 1

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 22/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Kamlesh Singh

Rate Limiting in ASP.NET Core


Rate limiting is a technique used to control the number of requests that a client can make to an
application within a specific time…

1 min read · Apr 26

15

Selim YILDIZ in Level Up Coding

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 23/24
8/15/23, 1:40 PM Repository Pattern and Unit of Work with ASP.NET Core Web API | by Yohan Malshika | Enlear Academy

Dapper vs EF Core: Which ORM Framework Should You Choose for


Your .NET Application
Detailed comparison of Dapper-EF Core and offer insights on when to choose one over the
other.

· 5 min read · Mar 13

29 2

See more recommendations

https://enlear.academy/repository-pattern-and-unit-of-work-with-asp-net-core-web-api-6802e1aa4f78 24/24

You might also like