Hexagonal Architecture: Ports and Adapters Pattern

Introduction to Hexagonal Architecture

Hexagonal Architecture, also known as Ports and Adapters, was introduced by Alistair Cockburn. It aims to create loosely coupled application components that can be easily connected to their software environment.

Core Concepts

The Domain (Hexagon Center)

The core business logic lives at the center, completely independent of external concerns. It contains entities, value objects, domain services, and business rules.

Ports

Ports are interfaces that define how the outside world can interact with your domain. There are two types:

  • Driving Ports (Primary): Define how external actors use your application (e.g., API controllers)
  • Driven Ports (Secondary): Define what your application needs from external services (e.g., repositories)

Adapters

Adapters implement ports to connect your domain to the outside world:

  • Driving Adapters: REST controllers, CLI commands, message handlers
  • Driven Adapters: Database repositories, external API clients, file system handlers

Implementation Example

Domain Layer

// Domain Entity
public class Order {
    public Guid Id { get; private set; }
    public OrderStatus Status { get; private set; }
    
    public void Ship() {
        if (Status != OrderStatus.Paid)
            throw new DomainException("Order must be paid before shipping");
        Status = OrderStatus.Shipped;
    }
}

Driven Port (Interface)

// Port - defined in domain layer
public interface IOrderRepository {
    Task<Order> GetById(Guid id);
    Task Save(Order order);
}

Driven Adapter (Implementation)

// Adapter - in infrastructure layer
public class SqlOrderRepository : IOrderRepository {
    private readonly DbContext _context;
    
    public async Task<Order> GetById(Guid id) {
        return await _context.Orders.FindAsync(id);
    }
    
    public async Task Save(Order order) {
        _context.Orders.Update(order);
        await _context.SaveChangesAsync();
    }
}

Application Service

public class ShipOrderUseCase {
    private readonly IOrderRepository _repository;
    
    public async Task Execute(Guid orderId) {
        var order = await _repository.GetById(orderId);
        order.Ship();
        await _repository.Save(order);
    }
}

Benefits

  • Testability: Domain logic can be tested without infrastructure
  • Flexibility: Swap adapters without changing domain
  • Focus: Domain remains pure business logic
  • Independence: Technology decisions are deferred

Project Structure

src/
โ”œโ”€โ”€ Domain/
โ”‚   โ”œโ”€โ”€ Entities/
โ”‚   โ”œโ”€โ”€ ValueObjects/
โ”‚   โ””โ”€โ”€ Ports/
โ”œโ”€โ”€ Application/
โ”‚   โ””โ”€โ”€ UseCases/
โ””โ”€โ”€ Infrastructure/
    โ”œโ”€โ”€ Persistence/
    โ”œโ”€โ”€ Api/
    โ””โ”€โ”€ ExternalServices/

Conclusion

Hexagonal architecture creates clear boundaries that make your application more maintainable and testable. The initial investment in structure pays dividends as your application grows.

๐Ÿ“šTechnical Insights & Industry Trends

Insights & Knowledge Hub

Explore in-depth articles on software development, digital transformation, and emerging technologies. Learn from real-world experience.

Browse by Topic

๐Ÿ…ฐ๏ธ
ArchitectureJan 2024

Why Angular SSR Beats React for SEO in 2024

A comprehensive comparison of server-side rendering implementations and their impact on search engine optimization, performance, and user experience.

๐Ÿ”Œ
ArchitectureDec 2023

Microservices: When to Use and When to Avoid

Understanding the trade-offs of microservices architecture and making the right choice for your organization's scale, complexity, and team structure.

๐Ÿ—๏ธ
System ArchitectureJan 2024

Essential Design Patterns for Enterprise Systems

Master the fundamental design patterns that every software architect should know for building scalable, maintainable enterprise applications.

๐Ÿ—๏ธ
System ArchitectureJan 2024

Domain-Driven Design: A Practical Guide

Learn how to apply Domain-Driven Design principles to create software that truly reflects business requirements and scales with organizational complexity.

๐Ÿ—๏ธ
System ArchitectureDec 2023

Event-Driven Architecture: Complete Implementation Guide

Build loosely coupled, scalable systems using event-driven architecture patterns with practical examples using Kafka, RabbitMQ, and Azure Service Bus.

๐Ÿ—๏ธ
System ArchitectureDec 2023

RESTful API Design: Best Practices and Patterns

Design APIs that developers love to use. Learn REST principles, versioning strategies, error handling, and documentation best practices.

Deep Dives into Key Areas

๐Ÿ—๏ธ

System Architecture

Design patterns and architectural decisions

12 Articles
โ˜๏ธ

Cloud Computing

AWS, Azure, and cloud-native development

8 Articles
โšก

Performance

Optimization and scalability techniques

6 Articles
๐Ÿค–

AI & Machine Learning

Practical AI applications in enterprise

5 Articles
๐Ÿ”’

Security

Best practices and compliance

7 Articles
๐Ÿ“ฑ

Modern Frontend

Angular, React, and UI/UX best practices

10 Articles

Have a Project in Mind?

Let's turn your ideas into reality. Schedule a free consultation to discuss how we can help transform your business.