Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Nov 25, 2022

Hexagonal Architecture ASP.NET Core

Автор:
Amit Naik
Источник:
Просмотров:
5747

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 kick-off project which will have all essential things integrated to it. When we have to start with a new project, then we should think of business. When 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 order wise, 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

What is Hexagonal Architecture

It is Architecture pattern which is introduced by Alistair Cockburn in 2005, which will solve problems in maintaining application. In traditional architecture, where we use 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 is based on the inversion of control principle. It’s composed of domain concentric architecture where layers interface with each other towards the Domain (Entities/Classes).

Main benefit of Hexagonal architecture is plug & play, flexibility and de-coupling. In this approach, we can see that all the Layers are dependent only on the Domain layer.

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. Rest all logic will be remain same.
  • Testability: As it decoupled all layers, so it is easy to write test case for each components.
  • Adaptability/Enhance: Adding new way to interact with application is very easy.
  • Sustainability: We can keep all third party libraries in Infrastructure layer and hence maintenance will be easy.
  • Database Independent: Since database is separated from data access, it is quite easy 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 organised: Project is well organised 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).
  • Bunch of layers: For implementing small application like CRUD operation, then too bunch of layers should be implemented.

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 center and never depends on any other layer. It is 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) which has business logic. and it is keep 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 where we have implement 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 final build of project, where it all begin.

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.

Step 2: Create Project

Select project type as WebAPI, and select Hexagonal Architecture.

Step 3: Select Hexagonal Architecture project template

Select project type as Web API, and select Hexagonal Architecture.

Step 4: Project is ready

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.

Swagger UI

Swagger UI https://localhost:44377/OpenAPI/index.html

** Change port number according to your application.

What problem does this solution solve

App generator solution includes all essential libraries with best practice, which will helps quick start project. Developer can concentrate on Business requirement and build entities. This helps save lots of development time.

Below are some essentials libraries which is already included in project with best practice built on Hexagonal architecture.

  1. Entity Framework Core
  2. Dependency injection
  3. Logging-Serilog
  4. Authentication
  5. Swagger/ OpenAPI
  6. Error handling
  7. Unit testing via NUnit
  8. Versioning

How does this help someone else

This solution helps for developer who can save development time and concentrate on Business module. And if he/she with less experience then it helps to maintain best practices in project (like clean code).

How does the code actually work

This is project template which is hosted in marketplace.visualstudio.com. Download this extension from marketplace and install in your visual studio. While creating project select this template.

Conclusion

In this article, we have seen what is Hexagonal Architecture and the difference between Design, Architecture pattern and Architecture Style. Project template will help us to quick start application.

Похожее
Jun 1
Author: Akalanka Dissanayake
Welcome to the first instalment of our comprehensive guide on securing your web applications with token authentication using ASP.NET Identity in .NET 8. In this part, we delve into the backbone of our authentication system — the Web API. We...
Oct 26, 2023
Author: Matt Bentley
How to implement CQRS in ASP.NET using MediatR. A guided example using CQRS with separate Read and Write models using Enity Framework Core for Commands and Dapper for Queries. When people think about CQRS they often think about complex, event-driven,...
Feb 7, 2021
Author: Manikanta Pattigulla
Overview In this article, I'll explain about the best possible ways to implement the web API, designing of great web API and finally, the things to remember while implementing API. How to design or build great Web API Applications? Basically...
Jan 11, 2023
Author: Nitesh Singhal
Database Setup with DbUp + Postgresql + Dapper in ASP.Net Core In this tutorial, we are going to explore how we can setup our database on startup when using Dapper for accessing database. When using Dapper, one of the key...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Проблема понимания существующего кода, или Как делать иногда [не] надо
Рассуждение на тему, какую базу данных выбирать
Hangfire — планировщик задач для .NET
Стили именования переменных и функций. Используйте их все
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Программист 2020: Терминатор отдыхает
Как избавиться от прокрастинации до того, как она разрушит вашу карьеру
Зарплата по результатам собеседования — лучший способ сократить отклики на вакансию, а тестовые задания — избыточны
10 продвинутых способов писать в консоль помимо console.log
Использование SQLite в .NET приложениях
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile