The user wants a domain-driven architecture refactor.
This involves:
Bounded Contexts: Identifying and defining these.
Aggregate Boundaries: Defining consistency boundaries within contexts.
Anti-Corruption Layers (ACL): Handling communication between contexts (especially legacy vs. new).
I need to create a conceptual mapping or a refactoring plan. It shouldn't be just code; it needs architectural diagrams (text-based) and strategic guidance.
Scenario:
To make this concrete, I'll invent a hypothetical legacy monolithic system (e.g., an E-commerce platform) and show how to refactor it into DDD-style microservices or modular monoliths.
Structure of the Response:
Executive Summary: Briefly explain what we are doing (Monolith -> DDD).
Phase 1: Domain Discovery & Context Mapping: How to identify the contexts.
Phase 2: Defining Bounded Contexts: The actual mapping.
Phase 3: Aggregate Design: Breaking contexts into aggregates.
Phase 4: Integration & Anti-Corruption Layers: How they talk.
Code/Structure Example: Concrete file structure or code snippets.
This is crucial. When Sales talks to Inventory, they shouldn't share database tables.
If Inventory is still legacy (SQL), but Sales is new (Service), Sales needs an ACL to translate "Legacy Inventory DB rows" into "Inventory Domain Objects".
Refining the "Design":
I will present a structured approach:
The Visual Map (ASCII art).
The Strategic Patterns (Contexts, Aggregates).
The Tactical Implementation (ACL Code structure).
Specifics for ACL:
Let's say we are extracting "Billing" from the "Sales" monolith.
Billing needs to know when an order is placed.
Legacy way: Billing queries the Orders table directly.
New way: Billing listens to an OrderPlaced event.
ACL Role: If the legacy system doesn't publish events yet, the ACL might wrap the legacy DB call or implement a "ChangeListener" to synthesize the event.
Aggregates:
Focus on Transaction Boundaries.
Example: Order and Payment should probably be separate aggregates. Why? Because validating a credit card takes time and might fail, but the Order exists. However, for the refactor, we need to separate the logic.
Let's build a "Modular Monolith" example. It's safer to refactor into a modular monolith first before microservices.
Project: ECommerceSystem
Module: SalesContext
Domain/Model/Order (Aggregate)
Module: InventoryContext
Domain/Model/Product (Aggregate)
Interface: ACL/InventoryAdapter (Sales uses this to talk to Inventory).
Self-Correction/Review during drafting:
Make sure to distinguish between the Strategic design (Context Map) and Tactical design (Aggregates).
The ACL is the bridge.
I should provide a mapping from "Old World" (Database tables) to "New World" (Domain Models).
Final Plan:
Scenario: Refactoring a Legacy E-Commerce Monolith.
Aggregate Boundary Mapping: Define roots and invariants.
Integration Architecture: Draw the ACL logic.
Code Skeleton: Show how the folder structure and interfaces look.
Let's generate the response.
This design outlines a refactor strategy for a hypothetical legacy E-Commerce Monolith transitioning to a Domain-Driven Modular Architecture.
We will move from a database-coupled system to distinct Bounded Contexts, define Aggregate boundaries to ensure consistency, and implement Anti-Corruption Layers (ACL) to isolate the new domain logic from the legacy schema.
1. The Strategic Map: Bounded Contexts (BC)
First, we identify the distinct domain models by looking at where language changes. In the legacy system, "Product" meant everything from a catalog item to a shipping box. We split this based on Ubiquitous Language.
Context Name
Responsibility
Key Domain Concepts
Catalog Context
Browsing, searching, and product details.
Product, Category, Review, SearchIndex
Inventory Context
Stock levels, warehousing, and reservations.
StockItem, Warehouse, Reservation
Order Context
Checkout process and order lifecycle.
Order, Cart, Payment, Invoice
Shipping Context
Logistics and fulfillment.
Shipment, TrackingNumber, Carrier
2. The Tactical Map: Aggregate Boundaries
Aggregates are consistency boundaries. They protect Invariants (business rules that must always be true).
Context: Order Management
Aggregate Root:Order
Entities:OrderLine, Address
Value Objects:Money, OrderId, OrderStatus
Invariant: An order cannot exceed $10,000 total without manager approval.
Boundary Rule: External contexts (like Shipping) cannot modify the Order directly. They can only reference it by OrderId.
Context: Inventory
Aggregate Root:StockKeepingUnit (SKU)
Entities: None (often purely rooted in the SKU)
Value Objects:Quantity, WarehouseLocation
Invariant: Quantity on hand cannot go below zero.
Boundary Rule: When an Order is placed, the Inventory Context creates a Reservation, but it does not hold a reference to the Order Entity, only an OrderId Value Object.
3. The Architecture: Code & Directory Structure
We will adopt a Modular Monolith approach for the refactor. This keeps deployment simple while strictly separating domains.
text
/src
/CatalogContext
/Domain (Pure C# classes, no DB dependency)
/Aggregates
/ValueObjects
/Events
/Application (Use Cases / Command Handlers)
/Infrastructure (EF Core Repository implementation)
/Interfaces (Controllers / GraphQL)
/InventoryContext
/Domain
/Aggregates
/StockItem.cs
/Infrastructure
/AntiCorruption <-- The ACL Lives Here
/OrderContext
...
4. The Bridge: Anti-Corruption Layers (ACL)
This is the most critical part of the refactor. The Inventory Context needs to reserve stock when the Order Context creates an order.
In the legacy system, this was a SQL join: INSERT INTO inventory WHERE order_id = ?.
In the new system, the Inventory Context must own its own data.
Scenario: Order Created → Reserve Stock
We need an ACL to translate the Order Domain Model into the Inventory Domain Model so the Inventory context remains pure.
Implementation Design
1. The Event (The Trigger)
The Order Context publishes an event that contains only primitive types or shared Value Objects (DTOs), not Entities.
csharp
// Order Context publishes this
public record OrderPlacedEvent(
Guid OrderId,
List<OrderLineDto> Lines,
DateTime OccurredOn
);
public record OrderLineDto(Guid ProductId, int Quantity);
2. The ACL (The Translator)
This layer sits at the edge of the Inventory Context. It listens to the external event and converts it into an internal Inventory Command.
csharp
// Inside InventoryContext/Infrastructure/AntiCorruption
public class OrderPlacedTranslator
: IEventHandler<OrderPlacedEvent> // Subscribing to external bus
{
private readonly ICommandHandler<ReserveStockCommand> _internalHandler;
public OrderPlacedTranslator(ICommandHandler<ReserveStockCommand> internalHandler)
{
_internalHandler = internalHandler;
}
public async Task Handle(OrderPlacedEvent externalEvent)
{
// 1. Validation: Does this event make sense for us?
if (!externalEvent.Lines.Any()) return;
// 2. Translation: Map external DTO to Internal Command
var internalCommand = new ReserveStockCommand(
ReferenceId: externalEvent.OrderId.ToString(), // String prevents tight coupling
Items: externalEvent.Lines.Select(l => new ReservationItem(
ProductId: l.ProductId,
Amount: l.Quantity
)).ToList()
);
// 3. Dispatch: Send to the pure domain handler
await _internalHandler.Handle(internalCommand);
}
}
3. The Domain Logic (Pure)
The Inventory aggregate receives a clean command, unaware that the source was an "Order".
csharp
// Inside InventoryContext/Domain
public class StockItem : AggregateRoot
{
public Guid ProductId { get; private set; }
public int AvailableQuantity { get; private set; }
// Pure business logic, no DB calls, no "Order" references
public void ReserveQuantity(string referenceId, int amount)
{
if (AvailableQuantity - amount < 0)
{
throw new InsufficientStockException(ProductId);
}
AvailableQuantity -= amount;
// Raise domain event: StockReserved
}
}
5. Refactoring Roadmap
Isolate the Schema: Create separate database schemas (or databases) for each context. orders.*, inventory.*.
Introduce Value Objects: Replace raw primitives (int, string) in your entities with Value Objects (Money, Sku) to encapsulate validation.
Define Aggregates: Identify the "Root" entity for every transaction. Ensure no other object modifies the Aggregate's children directly.
Implement ACLs: Stop contexts from querying each other's tables directly. Create the ACL "Translator" classes to handle communication via events/queues.
Drop Foreign Keys: Once the ACLs are handling consistency via eventual consistency, remove the strict SQL Foreign Keys between contexts.