Поиск  
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
Источник:
Просмотров:
5698

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.

Похожее
Feb 12
Author: Kartik
Application Insights - Telemetry 1. How do I instrument (monitor/record/enabling to capture telemetry) an application? Autoinstrumentation - if you don’t have access to source code You only need to install the Application Insights SDK if: You require custom events and...
Jul 22
Author: Ankit Sahu
Introduction In this article, we are going to discuss What Entity Framework is and How we can implement it in the .Net 8 project. This is a continuation of part 1, so if you are new to this article, please...
Jan 18, 2023
Author: Jay
Aha! There is always something intimidating about Dependency Injection. I distinctly remember a couple of years ago, telling a .Net recruiter for a contract project, that, “I had no idea what DI is” He immediately stopped talking to me. It’s...
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...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Почему вы никогда не должны соглашаться на собеседования с программированием
«Великое увольнение» продолжается: теперь с работы уходят даже боссы
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
5 приемов увеличения продуктивности разработчика
Зарплата по результатам собеседования — лучший способ сократить отклики на вакансию, а тестовые задания — избыточны
9 тяжёлых уроков, которые я усвоил за 18 лет разработки
8 вещей, которых не должен бояться разработчик
Рассуждение на тему, какую базу данных выбирать
Scrum: 12 терминов, которые нужно запомнить
Hangfire — планировщик задач для .NET
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile