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

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.

Похожее
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...
Aug 27
Author: Anton Martyniuk
Multitenancy is a software architecture that allows a single instance of a software application to serve multiple customers, called tenants. Each tenant's data is isolated and remains invisible to other tenants for security reasons. This architecture is commonly used in...
Feb 10, 2023
Author: Abdelmajid BACO
A Quick Guide to Transient, Scoped, and Singleton in C#. In C#, the Transient, Scoped, and Singleton scopes are options for controlling the lifetime of objects which are created by dependency injection. Transient Transient objects are created each time they...
Sep 5
Author: Jay Krishna Reddy
Introduction According to the people who designed it, OData (the Open Data Protocol) is “the best way to Rest”. OData is essential, a way to try and standardize REST. It’s an open protocol that allows the creation and consumption of...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Стили именования переменных и функций. Используйте их все
10 историй, как «валят» айтишников на технических интервью
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Семь итераций наивности или как я полтора года свою дебютную игру писал
Вопросы с собеседований, которые означают не то, что вы думаете
Путеводитель по репликации баз данных
5 приемов увеличения продуктивности разработчика
Топ 8 лучших ресурсов для практики программирования в 2018
Использование SQLite в .NET приложениях
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile