Clean Architecture ও Hexagonal Architecture

লেসন ১১ / ৫০

Clean Architecture

┌────────────────────────────┐
│  Frameworks (Web, DB, UI)        │
│  ┌──────────────────────┐  │
│  │ Interface Adapters            │  │
│  │ ┌──────────────────┐  │  │
│  │ │ Use Cases               │  │  │
│  │ │ ┌──────────────┐  │  │  │
│  │ │ │  Entities          │  │  │  │
│  │ │ └──────────────┘  │  │  │
│  │ └──────────────────┘  │  │
│  └──────────────────────┘  │
└────────────────────────────┘

Dependency Rule ⭐

Dependency শুধু ভিতরের দিকে। Inner outer-কে জানে না।

Entities (innermost)

public class Order {
    public int Id { get; private set; }
    public List<OrderItem> Items { get; }
    public decimal Total => Items.Sum(i => i.Price * i.Qty);
    public void Confirm() { /* domain rule */ }
}

Use Cases

public class PlaceOrderUseCase {
    IOrderRepository _orders;
    IPaymentGateway _payment;
    public async Task<int> HandleAsync(Request r) {
        var order = new Order(r.Items);
        await _payment.ChargeAsync(order.Total);
        return await _orders.AddAsync(order);
    }
}

Adapters

// Controller adapter HTTP → Use Case
// Repository adapter EF → IOrderRepository

Hexagonal (Ports & Adapters)

HTTP Adapter ↘
            Port → Core Domain ← Port
DB Adapter ↗                       ↖ Email Adapter

Port & Adapter

// Port (in core)
public interface INotificationPort {
    Task SendAsync(string to, string msg);
}
// Adapter (outside)
public class SmtpEmailAdapter : INotificationPort {}
public class FakeAdapter : INotificationPort {}  // test

Project Structure

MyApp/
├── MyApp.Domain/        # Entities (no deps)
├── MyApp.Application/   # Use Cases, Ports
├── MyApp.Infrastructure/# Adapters
└── MyApp.Web/           # ASP.NET (composition root)

Benefits

  • Testability — domain framework-free
  • Replaceability — DB swap easy
  • Long-term maintainability

Drawbacks

Learning curve, initial boilerplate, small CRUD-এ over-engineering।