In this article, we will learn about clean architecture and will walk you through a sample CRUD API in .NET 8.0.

We will use the following tools, technologies, and frameworks in this sample.

Before starting with the sample app, let us understand the clean architecture and its benefits.

The goal of software architecture is to minimize the human resources required to build and maintain the required system. ? Robert C. Martin, Clean Architecture.

Clean Architecture explained

Clean Architecture is the system architecture guideline proposed by Robert C. Martin also known as Uncle Bob. It is derived from many architectural guidelines such as Hexagonal Architecture, Onion Architecture, etc.

Advantages of clean architecture

So now I have an understanding of clean architecture. Before starting the sample API let us briefly review the Dapper.

Dapper explained

Along with Dapper in this article, we will use Repository Pattern and Unit of Work and show you how Dapper can be used in an ASP.NET 8.0 API following Repository Pattern and Unit of Work.

Solution and Project Setup

First of all, create a new table that’ll be used to perform the CRUD operation. You can use the scripts shared under the CleanArch.Sql/Scripts folder of the code sample.

Once our back end is ready, Open Visual Studio 2022 create a blank solution project, and name it to CleanArch.

CleanArch

Set Up the Core Layer

Under the solution, create a new Class Library project and name it CleanArch.Core.

Core Layer

Add a new folder Entities and add a new entity class with the name Contact.

public class Contact
{
    public int? ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}

One thing to note down here is that the Core layer should not depend on any other Project or Layer. This is very important while working with Clean Architecture.

Set Up the Application Layer

Set Up Logging

Set Up SQL Project

Set Up Infrastructure Layer

Set up API Project

Set up a Test Project

Build and Run Test Cases

Build the solution and run the code coverage, this will run all the test cases and show you the test code coverage.

Test Cases

Run and Test API

Run the project and test all the CRUD API methods. (Make sure CleanArch.API is set as a startup project).