The user wants a "domain service extraction roadmap."
The goal is to move logic from Controllers into Aggregate Roots (Domain Layer) and Application Services (Application Layer).
This is a classic refactoring scenario in Domain-Driven Design (DDD): moving from a "Transaction Script" or "Anemic Domain Model" (where controllers do everything) to a "Rich Domain Model" separated by layers.
1. Analyze the Current State vs. Desired State:
- Current: Fat Controllers. Logic is embedded in HTTP handlers. Hard to test, hard to reuse, business rules are scattered.
- Desired:
- Application Services: Orchestrate use cases, handle transaction management, infrastructure calls (repositories, external APIs). They are thin coordinators.
- Domain Layer (Aggregate Roots/Entities): Contain business rules, state changes, invariants protection. No infrastructure dependency.
2. Structure the Roadmap:
A roadmap needs phases. It shouldn't just be a list of techniques. It needs a chronological flow.
- Phase 1: Analysis & Preparation (Identifying what to move).
- Phase 2: The "Low-Hanging Fruit" (Extracting Application Services).
- Phase 3: Deep Dive (Extracting Domain Logic into Aggregates).
- Phase 4: Refinement & Polish (Domain Services, Specifications).
- Phase 5: Verification & Maintenance.
3. Drafting the Content for Each Phase:
-
Phase 1: Discovery & Assessment
- Need to identify "Business Logic" vs. "Plumbing".
- Identify Invariants (rules that must always be true).
- Identify Aggregates (clusters of data treated as a unit).
-
Phase 2: Introducing Application Services (The "Orchestration" Layer)
- Why? Controllers shouldn't talk directly to repositories usually, and definitely shouldn't manage transactions or mapping.
- Action: Create a service class per Controller or per Use Case.
- Move: Transaction scopes, fetching data, calling external APIs, mapping DTOs.
-
Phase 3: Enriching the Domain (Moving Logic into Aggregates)
- This is the core DDD move.
- Look for
if (x > y) logic in controllers/services.
- Move it to methods like
order.Complete() or user.ChangeEmail().
- Why? To protect invariants.
- The "Tell, Don't Ask" principle.
-
Phase 4: Handling Edge Cases (Domain Services & Specifications)
- What if logic doesn't fit in one entity? -> Domain Service.
- What if logic is complex query logic? -> Specification Pattern or Repository method.
-
Phase 5: Testing & Cleanup
- Unit tests should now target the Domain Layer, not the Controller.
- Controllers become thin wrappers.
4. Refining the Steps & Providing Concrete Examples:
The user needs actionable advice.
- Bad Code: Controller checks
if user.isActive.
- Refactored:
user.Activate().
5. Structuring the Output:
I should use a tiered approach:
- Introduction: Context (Anemic vs. Rich).
- Phase 1: Identification.
- Phase 2: Application Layer Extraction.
- Phase 3: Domain Layer Extraction (Aggregates).
- Phase 4: Domain Services (Cross-cutting logic).
- Phase 5: Validation & Iteration.
- Code Examples: Crucial for showing the transition.
6. Self-Correction/Review during drafting:
- Initial thought: Move everything to Aggregates immediately.
- Correction: No, usually it's safer to extract to Application Services first to get the controller thin, then push down from Application Service to Domain. If you try to jump straight from Controller to Domain, you might get stuck on infrastructure dependencies. The roadmap should reflect this "pushing down" motion.
7. Key Concepts to mention:
- Dependency Injection.
- DTOs vs. Domain Models.
- Transaction Management (Unit of Work).
- Invariants.
8. Final Polish:
Organize with clear headings, bullet points, and code snippets comparing "Before" and "After". (This aligns with the prompt's request for a "roadmap").
(Self-Correction during output generation): Ensure I distinguish between Application Services (Use Cases) and Domain Services (Business Logic that doesn't fit an entity). The prompt specifically asks for extraction into "Aggregate Roots and Application Services". I will focus primarily on those two.
Let's write the roadmap.
This roadmap outlines a step-by-step process to refactor a "Fat Controller" architecture into a clean, Domain-Driven Design. The goal is to strip controllers of business logic, moving it into Application Services (orchestration) and Aggregate Roots (business rules).
The Architecture Target
- Controller: Accepts HTTP request, validates DTOs, calls Application Service, returns HTTP response. (Zero business logic).
- Application Service: Orchestrates use cases. Loads aggregates, calls repository, saves changes. (Coordination only).
- Aggregate Root: Contains the data and the business rules. Enforces invariants. (The Brain).
Phase 1: Stabilization & Preparation
Goal: Create a safety net and define boundaries before writing new code.
- Characterize Logic:
Identify the "Fat Controllers." Look for:
if/else chains checking business rules.
- Direct database queries inside the controller.
- Calculations (e.g.,
total = price * qty).
- Write Characterization Tests:
Since you are moving logic, you need to ensure behavior doesn't change. Write integration tests (or unit tests) against the current controller endpoints to capture current outputs for given inputs.
- Define the Aggregates:
Identify the nouns in your controller. Is the
OrderController managing an Order? That is your Aggregate Root.
Phase 2: Extract Application Services (The "Orchestrators")
Goal: Remove infrastructure and orchestration concerns from the controller.
- Create the Service Class:
Create a class named
[Entity]Service or [Entity]CommandHandler (e.g., OrderService).
- Move Orchestration Logic:
Move code that deals with fetching data, saving data, or calling external APIs from the Controller to the Service.
- Controller calls:
await _orderService.PlaceOrderAsync(dto).
- Handle Transactions:
Ensure the Application Service handles the Unit of Work (Transaction). The controller should not open or commit transactions.
Status Check: Your controller is now thin, but your Service is fat. This is an intermediate step.
Phase 3: Push Logic to Aggregate Roots (The "Brains")
Goal: Move business rules out of the service layer and into the domain entities.
- Identify "Anemic" Setters:
Look for code in your Service like:
// Bad: Logic in Service
if (order.Status == Status.Shipped) throw new Exception();
order.Status = Status.Cancelled;
order.CancelledAt = DateTime.UtcNow;
- Create Domain Methods:
Replace property setters with intention-revealing methods on the Aggregate Root.
// Inside the Order Aggregate Root
public void Cancel()
{
if (Status == Status.Shipped)
throw new InvalidOperationException("Cannot cancel shipped order.");
Status = Status.Cancelled;
CancelledAt = DateTime.UtcNow;
// Raise Domain Event: OrderCancelled
}
- Refactor Service to "Tell, Don't Ask":
Change the Service to simply load the aggregate and tell it to act.
// Inside Application Service
var order = await _repo.GetByIdAsync(id);
order.Cancel(); // Logic is now inside the entity
await _unitOfWork.SaveChangesAsync();
Phase 4: Isolate Domain Services
Goal: Handle logic that doesn't naturally fit inside a single Entity.
Sometimes logic involves multiple aggregates or external calculations (e.g., "Calculate tax based on user location and item category").
- Create Interface in Domain Layer:
Define
ITaxCalculator in your Domain project.
- Implement in Infrastructure:
Implement the logic in an infrastructure service.
- Invoke via Aggregate or Application Service:
- Option A: Pass the service to the Aggregate method:
order.CalculateTotal(taxCalculator).
- Option B: Calculate in the App Service and pass the result:
order.SetTax(taxAmount).
Phase 5: Cleanup & Optimization
Goal: Remove technical debt and refine the API.
- Strict DTO Mapping:
Ensure controllers return DTOs, not Domain Entities. Use AutoMapper or manual mapping to ensure internal domain structure isn't leaked to the API client.
- Remove Public Setters:
Ensure your Aggregate Roots have
private set on their properties. The only way to change state should be via the methods you created in Phase 3.
- Remove Unused Code:
Delete old helper classes or static methods that were duplicating the logic you just moved.
Code Example: The Transformation
Step 1: The "Fat Controller" (Starting Point)
[HttpPost]
public async Task<IActionResult> Checkout(int userId)
{
// Logic mixed with infrastructure
var user = _context.Users.Find(userId);
var cart = _context.Carts.Include(x => x.Items).FirstOrDefault(x => x.UserId == userId);
if (cart == null || !cart.Items.Any()) return BadRequest("Cart empty");
// Business logic in controller
if (user.IsBanned) return Forbid("User is banned");
var order = new Order
{
UserId = userId,
CreatedAt = DateTime.UtcNow,
Status = Status.Pending
};
foreach(var item in cart.Items)
{
order.Total += item.Price * item.Quantity;
order.Items.Add(item);
}
_context.Orders.Add(order);
_context.SaveChanges();
return Ok(order.Id);
}
Step 2: Application Service Extraction
Controller becomes thin, Service handles flow.
// Controller
[HttpPost]
public async Task<IActionResult> Checkout(int userId)
{
var orderId = await _orderService.CheckoutAsync(userId);
return Ok(orderId);
}
// Application Service
public async Task<int> CheckoutAsync(int userId)
{
var user = await _userRepo.GetByIdAsync(userId);
var cart = await _cartRepo.GetByUserIdAsync(userId);
// Logic is still here temporarily
if (user.IsBanned) throw new BusinessException("User is banned");
var order = new Order(userId, cart.Items);
await _orderRepo.AddAsync(order);
await _unitOfWork.CommitAsync();
return order.Id;
}
Step 3: Domain Logic Extraction (Final State)
Logic moves to Domain. Service becomes a conductor.
The Aggregate Root:
public class Order : BaseEntity
{
public int UserId { get; private set; }
public decimal Total { get; private set; }
public List<Item> Items { get; private set; }
// Constructor ensures valid state upon creation
public Order(User user, Cart cart)
{
if (cart.IsEmpty) throw new DomainException("Cannot checkout empty cart");
if (user.IsBanned) throw new DomainException("Banned users cannot checkout");
UserId = user.Id;
Items = cart.Items;
CalculateTotal();
}
private void CalculateTotal()
{
Total = Items.Sum(x => x.Price * x.Quantity);
}
}
The Application Service (Simplified):
public async Task<int> CheckoutAsync(int userId)
{
var user = await _userRepo.GetByIdAsync(userId);
var cart = await _cartRepo.GetByUserIdAsync(userId);
// The Service just creates the object; the Object validates itself
var order = new Order(user, cart);
await _orderRepo.AddAsync(order);
await _unitOfWork.CommitAsync();
return order.Id;
}