How to utilize the unit of work pattern in ASP.NET Core

Uncategorized

In a lot of any company application, you will store and retrieve data from an information shop by performing CRUD operations (create, read, update, and delete). In this regard, there are several innovations and tools you can use. For example, you can pick from the offered ORM structures such as Entity Framework, Dapper, or NHibernate.However, the difficulties go beyond storing and retrieving data. You want to utilize a tool or a technique that helps you write recyclable, maintainable, and versatile code. For that, you can make use of design patterns such as the repository and unit of work patterns.We examined the repository design pattern in

an earlier post here. In this post, we’ll explore the system of work style pattern with appropriate code examples to show the principles covered.To use the code examples provided in this article, you must have Visual Studio 2022 installed in your system. If you do not currently have a copy, you can download Visual Studio 2022 here.

Develop an ASP.NET Core 7 Web API job in Visual Studio 2022 First off, let’s create an ASP.NET Core 7 job in Visual Studio 2022. Follow these actions: Launch the Visual Studio 2022 IDE. Click on”Create new job.”In the”Develop brand-new task” window, choose”

ASP.NET Core Web API “from the list of templates displayed. Click Next. In the”Configure your brand-new task “window, define the name and location for

  • the new project.
  • Additionally inspect the”
  • Place service and job in the same directory”check box, depending upon your preferences. Click Next.
  • In the “Extra
  • Details”window, leave the check box that says “Use controllers( uncheck to use minimal APIs )”inspected, since we’ll not be utilizing minimal APIs in this example. Leave the” Authentication Type”as “None”( default).
  • Make sure that the check boxes” Enable Open API Support,” “Configure for HTTPS,”and”Enable Docker” are unattended as we will not be using those features here. Click Develop. We’ll utilize this ASP.NET Core 7 Web API project
  • to work with the system of work style pattern in the sections below. What is the system of work design pattern?The unit of work style pattern assurances information stability and consistency in applications.
  • It makes sure that all changes made to numerous items in the application are committed to the database or rolled back. It provides an arranged and consistent way to handle database modifications and transactions.The primary goal of this design pattern is to preserve consistency and atomicity, ensuring that all modifications made to the database achieve success or fail together if there’s a problem. As an outcome, information consistency is maintained, and adjustments to the database are always

    precise. With the unit of work design pattern in place, developers can save effort and time by concentrating on service reasoning instead of database gain access to and management. Implementing the system of work style pattern in C# To execute the system of work design pattern, you must specify the operations that the unit of work supports in a user interface or a contract and then carry out these approaches in a concrete class. You can make the most of any information gain access to innovation you would like to utilize, such as Entity Framework, Dapper, or ADO.NET.A common system of work

    application would comprise the parts noted below: A user interface for the system of work. The operations that the system of work will carry out are specified by a contract or a user interface that contains the declaration of all the approaches for adding, altering, and erasing data and for devoting or rolling back changes to the database. A concrete implementation of the system of work interface. A concrete application of the interface we just described. This application will include all the operations that carry out any deals or information operations together with operations for rolling back or devoting changes. A repository class and its user interface. The code required to access or customize data is included in a repository class and its

  • user interface. Simply put, you must have a repository class that utilizes each of the interface’s approaches and an interface for your repository that specifies the permitted actions. So, let’s get started!Create a CustomDbContext class In Entity Structure or Entity Framework Core, a DbContext represents the entrance to the database. The following is the DbContext class that can be generated instantly when you’re utilizing Entity Framework Core. We’ll use this class numerous times in the code snippets that follow. public class CustomDbContext: DbContext ul>

    ) safeguarded override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder) public DbSet Authors Specify the interface for the unit of work Develop a new.cs file named IUnitOfWork.cs in your job and get in the following code.public user interface IUnitOfWork: IDisposable void Dedicate(); space Rollback(); IRepository Repository() where T: class; Execute the system of work concrete class Next, you must develop the concrete implementation of the IUnitOfWork user interface. To do this, develop a brand-new class called UnitOfWork in a file having the very same name with a.cs extension, and enter the following code.public class UnitOfWork: IUnitOfWork, IDisposable p>private bool disposed=incorrect; protected virtual void Dispose(bool getting rid of )if(! this.disposed). this.disposed = real; public space Dispose( ). Specify the repository interface A repository design pattern streamlines data gain access to by abstracting the logic from the other parts and modules of the application. Your things will be persisted without your having to work directly with the logic used to access the underlying database. In other words, a repository encapsulates the logic utilized to access the information source.The next action is to define the interface for your repository. This interface ought to supply the statements of the methods supported by the repository. Produce a brand-new interface named IRepository in a file called IRepository.cs and change the default generated code with the following code.public interface IRepository where T: class T GetById(things id); IList GetAll (); void Include(T entity );. Execute the repository user interface Lastly, you should implement the repository interface

    we just created. To do this, produce a

    new file named Repository.cs and replace the default created code with the following code.public class Repository: IRepository where T: class Register the DbContext As a perk, you ought to register the DbContext as a service in the Program.cs file so that you can take advantage of dependency injection to retrive DbContext circumstances in the Repository and UnitOfWork classes.There are two ways to do this: utilizing the AddDbContext approach or utilizing the AddDbContextPool approach. The AddDbContextPool technique is preferred since utilizing a pool of circumstances will help your application to scale.builder.Services.AddDbContextPool(o=> o.UseSqlServer (“Define the database connection string here …”) ); In this post, we built a genericrepository execution that uses an IRepository user interface and the Repository class. You can create a repository for a specific entity by producing a class that implements the generic IRepository interface as revealed below.public class AuthorRepository: IRepository Write code here to execute the members of the IRepository interface. Repositories and the unitof work design pattern develop an abstraction layer in between your company reasoning and the data gain access to layer, making life much easier for the developer. The system of work pattern utilizes a single transaction or a

    single system of work for several insert, update, and delete operations. These operations either be successful or failure as a whole system. To put it simply, all of the operations will be dedicated as one deal or rolled back as a single unit.Whereas the system of work pattern is used to aggregate several operations in a single transaction, repositories represent types that encapsulate the data gain access to logic, separating that issue from your application.

    Copyright © 2023 IDG Communications,Inc. Source

  • Leave a Reply

    Your email address will not be published. Required fields are marked *