A Clean Architecture for Building Web Applications with ASP.NET Core MVC C#

Overview

ASP.NET Core MVC is a robust framework for constructing web applications, and when combined with the Clean Architecture pattern, it can result in manageable and expandable solutions. In this piece, we will explore how to organise an ASP.NET Core MVC project using Clean Architecture principles, with code samples written in C#.

What is the Concept of Clean Architecture?

Clean Architecture is a software design principle that emphasizes the separation of concerns and maintainability by structuring the codebase into distinct layers. These layers typically encompass.

  • User Interface Layer
    This is where the presentation elements are located. In the context of ASP.NET Core MVC, it encompasses controllers, views, and view models.
  • Application Layer
    This layer houses the business logic of the application. It is responsible for handling user requests, processing data, and interacting with the domain layer.
  • Domain Layer
    This layer serves as the core of the application, defining the essential business entities, rules, and domain-specific logic. It should be independent of any infrastructure or application-specific code.
  • Infrastructure Layer
    This layer deals with external concerns such as data access, external services, and any infrastructure-related code. It should be isolated from the other layers.

Establishing a Clean Architecture Project

Let's begin by creating a new ASP.NET Core MVC project with Clean Architecture in mind.

Step 1. Creating a New ASP.NET Core MVC Project

We can utilise either the dotnet command-line tool or Visual Studio to create a fresh ASP.NET Core MVC project. Make sure that we have the ASP.NET Core SDK installed.

dotnet new mvc -n ZRCleanArchitectureApp

Step 2. Defining the Project Structure

Organise our project by segregating it into distinct folders for each layer.

  • ZRCleanArchitectureApp.Web
    This folder represents the presentation layer and contains controllers, views, and view models.
  • ZRCleanArchitectureApp.Application
    In this folder, we define application services and business logic.
  • ZRCleanArchitectureApp.Domain
    This folder is where we define our domain entities and business rules.
  • ZRCleanArchitectureApp.Infrastructure
    This folder is responsible for handling data access, external services, and infrastructure-related code.

Step 3. Implementing Clean Architecture

Defining Domain Entities

// ZRCleanArchitectureApp.Domain/Entities/Product.cs
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Implementing Application Services

// ZRCleanArchitectureApp.Application/Services/ProductService.cs
public class ProductService
{
    private readonly IProductRepository _productRepository;

    public ProductService(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    public async Task<IEnumerable<Product>> GetAllProductsAsync()
    {
        return await _productRepository.GetAllAsync();
    }

    // Add other business logic methods here
}

Creating Controllers

// ZRCleanArchitectureApp.Web/Controllers/ProductController.cs
public class ProductController : Controller
{
    private readonly ProductService _productService;

    public ProductController(ProductService productService)
    {
        _productService = productService;
    }

    public async Task<IActionResult> Index()
    {
        var products = await _productService.GetAllProductsAsync();
        return View(products);
    }

    // Add other action methods
}

Configuring Dependency Injection

In the Program.cs file, configure dependency injection for our services and repositories.

builder.Services.AddScoped<ProductService>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();

Summary

ASP.NET Core MVC Clean Architecture offers a structured approach to developing web applications that are maintainable, scalable, and easily testable. By separating concerns into distinct layers, we can focus on writing clean and modular code.

In this article, we have only scratched the surface of Clean Architecture. We can further enhance our project by adding validation, authentication, and authorisation mechanisms, as well as implementing unit tests to ensure the accuracy of our code.

Remember that Clean Architecture is a guideline, not a strict rule. Adapt it to our project's specific requirements and complexities, and always aim for simplicity and maintainability in our codebase.

The Code Examples are available on my GitHub Repository:   https://github.com/ziggyrafiq/Clean-Architecture-ASP.NET-Core-MVC

Please do not forget to follow me on LinkedIn https://www.linkedin.com/in/ziggyrafiq/ and click the like button if you have found this article useful/helpful.

Happy coding!


Capgemini
Capgemini is a global leader in consulting, technology services, and digital transformation.