
Hexagonal Architecture in .NET: the fastest (right) way
🟩🟩🟦 Confirmed
My goal is to provide you with a quick and easy-to-implement solution in order to adapt this architecture to your project. This story is .NET-oriented, but you could adjust its content for Java without effort.
Overview
Hexagonal Architecture has the wind in its sails. There are many blog posts about the theory but much fewer about practicals. But I need to introduce it before switching to the code.
Domain:
It’s the core of the system where all the business logic resides. We want to isolate it from both the driving and driven sides. Just remember one thing: no infrastructure code in the domain. (ex: Microsoft.AspNetCore.* or Microsoft.EntityFrameworkCore.* are forbidden here).
Driving (or primary) side:
Driving (or primary) actors are the ones that initiate the interaction with the application. Typically, your HTTP routes for an API or a Kafka consumer. (ex: Microsoft.AspNetCore.* should be found here).
Driven (or secondary) side:
The layer where we’ll find what your application needs, for example, a database adapter, is called by the application so that it fetches a specific data set from persistence. (ex: Microsoft.EntityFrameworkCore.* should be found here).
Main benefits:
- Easy to maintain: thanks to the decoupling provided by the hexagonal architecture, it is easy to add features without leading to refactoring. Indeed, changes in one area of the application don’t affect others.
- Easy to test: thanks to interfaces, you can mock dependencies and test each layer in isolation, as I have described here.
The term “hexagonal” comes from the graphical conventions that show the application component as a hexagonal cell. The purpose was not to suggest that there would be six borders but to leave enough space to represent the different interfaces needed between the component and the external world.

In practice
I am purposely bypassing the tests here to be as concise as possible. You could find some help to unit test the architecture in my previous story.
Domain
Consider an existing solution composed of an empty ASP.NET Core project named “Service.csproj”. Add a new class library project from the template list, name it “Domain.csproj” then remove the existing “Class1.cs” file. Edit the existing “Service.csproj” file to add a reference to the new “Domain” project.







