Nerd For Tech
Published in

Nerd For Tech

Implementing Unit Of Work And Repository Pattern With Dependency Injection In .Net 5

Unit of Work .Net 5.0

Introduction

All software program requires a statistics base framework wherein it communicates (CRUD) to save and get better data. Many available technology and frameworks on the market allow accessing databases smoothly and efficiently. To builders using Microsoft .Net technology, Entity Framework or Dapper have received recognition. but, the concern isn’t always the way to use those frameworks however the way to write code using those frameworks which are reusable, maintainable, and readable. this text will momentarily clarify the archive and unit of Work configuration instance to attend to all regular problems with records set admittance and enterprise cause exchanges. We likewise include some functional instances of a way to execute them in a regular .Net Core Project.

Source Code

Table of Contents

  • What is Repository & Unit of Work Pattern
  • Prerequisites
  • Setup the project
  • Implementing the Repository Pattern
  • Generic Repository Interface
  • Repository Classes
  • Repository and DbContext Injection
  • Dependency Injection
  • Unit of Work Interface Design
  • Unit of Work Implementation
  • Schema Execution
  • Wrapping the API Controller
  • Project Structure
  • Conclusion

What is Repository & Unit of Work Pattern?

The repository pattern is intended to create an abstraction layer between the data access layer and the business logic layer of an application. It is a data access pattern that prompts a more loosely coupled approach to data access. We create the data access logic in a separate class, or set of classes called a repository with the responsibility of persisting the application’s business model.

Unit of Work is referred to as a single transaction that involves multiple operations of insert/update/delete and so on kinds. To say it in simple words, it means that for specific user action (say registration on a website), all the transactions like insert/update/delete and so on are done in one single transaction, rather than doing multiple database transactions. This means, one unit of work here involves insert/update/delete operations, all in one single transaction.

Fig-1

Prerequisites

  • Visual Studio 2019 — Download from here
  • .Net 5.0 SDK — Download from here

Setup the Project

  1. Open Visual Studio and select “Create a new project” and click the “Next” button.
  2. Add the “project name” and “solution name” also the choose the path to save the project in that location, click on “Next”.
  3. Now choose the target framework “.Net 5.0” which we get once we install the SDK and also will get one more option to configure Open API support by default with that check box option.

Implementing Repository Pattern

Let us now jump into the code to set up a repository pattern to persist domain models. Here we need to add a new class library project OrderStore.Domain to add our Domain models and Repository Layer as below, the domain project represents the domain layer with necessary business logic and the Repository layer represents the persistence aspects. To keep things simple the domain layer contains two aggregates (Order and Product) with an entity each. The solution is set up as below

Fig-2

Order.cs

Product.cs

Generic Repository Interface

Generic Repository helps us to save and retrieve its persistent state from the database.

IGenericRepository.cs

Now the two entities represent Order and Product domain objects. Those two objects have their own collections since we add the Generic repository interfaces for each entity type to manage all the Crud operations. we can reuse the Generic Repository as below.

IOrderRepository.cs

IProductRepository.cs

Repository Classes

The Repository Layer implements the interfaces defined in each root. This allows the repository implementation to be abstracted away from the domain layer. The Repository instance uses EFCore to connect to a SQL Server instance and perform database actions. To use EFCore we need to install the below Nuget packages to OrderStore.Repository (Create a new project (Class Library)).

Fig-3

Before we implement the repository classes we need to implement the DbContext class to connect to the database. The DbContext implementation between the repository and the database.

ApplicationDbContext.cs

Now we have the DbContext class to connect with the database we can create the necessary implementations of the Repository used by the entities Order and Product. The repository classed can now inherit from the generic abstract repository class and implement functionality that is specific to that entity. This is one of the best advantages of the repository patterns we can now use named queries returning specific business data

OrderRepository.cs

ProductRepository.cs

Repository and DbContext Injection

To use the ApplicationDbContext and the repositories we need to be able to inject them in the tp dependency injection container. We can do that by creating an extension method in the repository layer as below

DependencyInjection.cs

we can now add the AddRepository in the startup class of the API. This makes it much easy to add the necessary dependencies at the appropriate layer.

Startup.cs

Unit of Work Interface Design

The Unit of Work interface for our code has to sit in the interfaces folder as same above.

IUnitOfWork.cs

Unit Of Work Implementation

The Unit of Work holds all the entities involved in a Business logic into a single transaction and either commit the transaction or rolls it back. The Complete implementation of the Unit Of Work interface is below.

UnitOfWork.cs

Schema Execution

Let’s add the migrations and update our Database. Run the below commands one after another in the package manager console, make sure you switch to OrderStore.Repository before executing the commands

add-migration ‘Initial’

update-database

Wrapping the API Controller

We can now inject the unit of work into our Order and Product Controller. We need to retrieve the repository and its related business logic via the Unit of Work. This will ensure that the Order and Product are going to perform the Database operations. I have added two APIs in Order Controller to fetch the data from the database and in the same way, also added two more APIs in the Product Controller to Post and update the Data to the Database.

OrderController.cs

ProductController.cs

Project Structure

Fig-4

With everything tied up, we can now run the project and fire up swagger to submit a get request at the Orders endpoint. Let’s see all our APIs under the swagger URL

Fig-5

GetOrders

Fig-6

Conclusion

The above article demonstrates the usage of Repository Pattern and Unit of work to ensure a clean design.

Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.

keep Learning …!

--

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Recommended from Medium

Deploying a Geo-Redundant Serverless RabbitMQ Cluster on Azure Using Pulumi for .NET

CS373 Spring 2022: Yifan Zhou: Final Entry

A Multi-Cloud and Multi-Cluster Architecture with Kubernetes

How to run the docker-compose from Intellij

May 2022 Development Recap for The Blockchain OS.

Functions in C Programming II

Marksman Revised: An Application of Flow to the Agile Methodology in Software Development Pt. 2

From 2/4 to 5/5, How IBM Quantum Transformed it!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jay Krishna Reddy

Jay Krishna Reddy

Full Stack Developer | Top Writer ✍🏻 Medium | C# Corner MVP 🏅| Cloud Enthusiast ☁️

More from Medium

Assign specific authorization scheme to endpoint in Swagger UI in .NET core

In-Memory Cache: Use of Memory Caching In .NET Core

How to implement Logging with Asp.Net Core, Elasticsearch and Kiabana

Using DateOnly with .Net 6 WebAPI and Entity Framework