Hexagonal Architecture In ASP.NET Core

In this article, you will see a Web API solution template which is built on Hexagonal Architecture with all essential features using .NET Core.

Introduction

 
This is a kick-off project which will have all essential things integrated into it. When we have to start with a new project, then we should think of the business needs. When the business requirement is ready, then we have to start focusing the business and we should be ready with basic/essential libraries.
 
We will see some important libraries in order, which should be integrated to our project for kick-off.
  • Essentials Libraries/ Steps to be Ready for ASP.NET Core
  • Application is implemented on Hexagonal architecture
  • Web API
  • Entityframework Core
  • Expection handling
  • Unit testing via NUnit
  • Versioning
  • Swagger UI
  • Loggings — seriLog
  • Health checks UI
  • JWT authentication

Table of Contents

  • What is Hexagonal Architecture
  • Benefits of Hexagonal Architecture
  • Disadvantages of Hexagonal Architecture
  • Layers of the Hexagonal Architecture
  • Getting Started with Hexagonal Architecture
  • Step 1: Download and install Visual Studio extension from project template
  • Step 2: Create Project
  • Step 3: Select Hexagonal Architecture project template
  • Step 4: Project is ready
  • Step 5: Build and run application
  • Diving inside the code snippets
  • What problem does this solution solve?
  • How does this help someone else?
  • How does the code actually work?
  • References
  • Conclusion

What is Hexagonal Architecture

 
It is an architecture pattern which was introduced by Alistair Cockburn in 2005, which will solve problems in maintaining applications in traditional architecture, which we used to implement by Database-centric architecture.
 
Hexagonal Architecture, or to call it properly, “Ports and Adapters pattern”, is driven by the idea that the application is central to your system. All inputs and outputs reach or leave the core of the application through a port that isolates the application from external technologies, tools and delivery mechanics.
 
Hexagonal Architecture In ASP.NET Core 
 

Benefits of Hexagonal Architecture

  • Plug & play
    We can add or remove adapter based on our development, like we can replace Rest adapter with GraphQL or gRPC adapter. The rest of the logic will be remain the same

  • Testability
    As it decoupled all layers, so it is easy to write a test case for each components

  • Adaptability/Enhance
    Adding a new way to interact with applications is very easy

  • Sustainability
    We can keep all third party libraries in Infrastructure layer and hence maintainence will be easy

  • Database Independent
    Since database is separated from data access, it is quite easy to switch database providers

  • Clean code
    As business logic is away from presentation layer, it is easy to implement UI (like React, Angular or Blazor)

  • Well organized
    Project is well organized for better understanding and for onboarding for new joinee to project
Disadvantages of Hexagonal Architecture
 
Domain layer will be heavy
 
Lots of logic will be implemented in Domain layer (sometimes called as Core layer)
 

Layers of the Hexagonal Architecture

 
In this approach, we can see that all the Layers are dependent only on the Core Layers.
 
Domain Api layer
 
Domain Api Layers (Core layer) is implemented in the center and never depends on any other layer. It is a contract for domain layer interaction (ports) so that primary and secondary adapters can implement the contract. This is also known and DIP or Dependency Inversion Principle Domain layer
 
Domain Layers (Business layer)
 
These layers have business logic and are kept clean with no other dependencies.
 
Rest Adapter layer
 
Rest Adapter also known as left port’s adapter and primary adapter where we implement restful service (i.e., GET, POST, PUT, DELETE, etc.)
 
Persistence Adapter layer
 
Rest Adapter, also known as right port's adapter and secondary adapter, is where we have implemented Entity framework core which already implements a repository design pattern. DbContext will be UOW (Unit of Work) and each DbSet is the repository. This interacts with our database using dataproviders
 
Bootstrap/Presentation Layer
 
This is the final build of project, where it all begins.
 
You will understand more when we start implementing the project below.
 

Getting Started with Hexagonal Architecture

 
Step 1
 
Download and install Visual Studio Extension from Project Template
 
Download and install Visual Studio extension from Microsoft marketplace.
 
Hexagonal Architecture In ASP.NET Core 
 
Step 2 - Create Project
 
Select project type as WebAPI, and select Hexagonal Architecture.
 
Hexagonal Architecture In ASP.NET Core 
 
Step 3 - Select Hexagonal Architecture Project Template
 
Select project type as Web API, and select Hexagonal Architecture.
 
Hexagonal Architecture In ASP.NET Core 
 
Step 4
 
Project Is Ready
 
Hexagonal Architecture In ASP.NET Core 
 
Step 5
 
Build and run application
 
Health check UI
 
Navigate to Health Checks UI https://localhost:44377/healthcheck-ui and make sure everything is green.
 
** Change port number according to your application
 
Hexagonal Architecture In ASP.NET Core 
 
Swagger UI
 
Swagger UI https://localhost:44377/OpenAPI/index.html
 
** Change port number according to your application
 
Hexagonal Architecture In ASP.NET Core 
 
Diving inside the code snippets
 
Will look inside all layers.
 
Domain Api layer code snippets
 
First we will see domain layer, here will create entities based on requirement. In this example, we have created Deal Model.
  1. public class BaseEntity  
  2. {  
  3.     [Key]  
  4.     public int Id { getset; }  
  5. }  
  6.   
  7. public class Deal : BaseEntity  
  8. {  
  9.       public string Name { getset; }  
  10.       public string Description { getset; }  
  11. }  
Domain layer code snippets
 
In this layer, we have created DealDomain which is derived from IRequestDeal interface.
  1. public class DealDomain : IRequestDeal where T : class  
  2. {  
  3.       private readonly DbSet table;  
  4.   
  5.       public DealDomain(ApplicationDbContext dbContext)  
  6.       {  
  7.             ApplicationDbContext _dbContext;  
  8.             _dbContext = dbContext;  
  9.             table = _dbContext.Set();  
  10.       }  
  11.       public T GetDeal(int id)  
  12.       {  
  13.             return table.Find(id);  
  14.       }  
  15.   
  16.       public List GetDeals()  
  17.       {  
  18.             return table.ToList();  
  19.       }  
  20. }   
Persistence layer code snippets
 
In Persistence layer, we will implement EntityFrameworkCore by creating ApplicationDbContext.
  1. public class ApplicationDbContext : DbContext  
  2. {  
  3.       public ApplicationDbContext()  
  4.       {  
  5.       }  
  6.       public ApplicationDbContext(DbContextOptions options) : base(options)  
  7.       {  
  8.       }  
  9.       public DbSet Deals { getset; }  
  10.       public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())  
  11.       {  
  12.             return base.SaveChangesAsync(cancellationToken);  
  13.       }  
  14. }   
Rest adapter code snippets
 
In Rest adapter, we implement Api by creating Controller by using DealController.
  1. [ApiController]  
  2. [Route("api/v{version:apiVersion}/[controller]")]  
  3. public class DealController : ControllerBase  
  4. {  
  5.       private readonly IRequestDeal _requestDeal;  
  6.   
  7.       public DealController(IRequestDeal requestDeal)  
  8.       {  
  9.             _requestDeal = requestDeal;  
  10.       }  
  11.   
  12.       // GET: api/deal  
  13.       [HttpGet]  
  14.       public IActionResult Get()  
  15.       {  
  16.             var result = _requestDeal.GetDeals();  
  17.             return Ok(result);  
  18.       }  
  19.   
  20.       // GET: api/deal/1  
  21.       [HttpGet]  
  22.       [Route("{id}", Name = "GetDeal")]  
  23.       public IActionResult Get(int id)  
  24.       {  
  25.             var result = _requestDeal.GetDeal(id);  
  26.             return Ok(result);  
  27.       }  
  28. }   
What problem does this solution solve?
 
An app solution inclues all essential libraries with best practices, which will helps quick start the project. Developer can concentrate on business requirements and build entities. This helps save lots of development time.
 
Below are some essentials libraries which are already included in a project with best practice built on Hexagonal architecture
  • Entityframework Core
  • Expection handling
  • Unit testing via NUnit
  • Versioning
  • Swagger UI
  • Loggings — seriLog
  • Health checks UI
  • JWT authentication
How does this help someone else?
 
This solution helps developers who can save development time and concentrate on business modules. And if he/she has less experience then it helps to maintain best practices in the project (like clean code)
 
How does the code actually work?
 
This is a project template which is hosted in marketplace.visualstudio.com. Download this extension from marketplace and install in your visual studio. While creating your project select this template.
 

Conclusion

 
In this article, we have seen what Hexagonal Architecture is. Project template will help us to quick start application.