CQRS and Event-Driven Architecture :👈 👉:Distributed Transactions: Saga Pattern and Outbox Pattern

Domain-Driven Design (DDD) with ASP.NET Core: Practical Enterprise Implementation

Domain-Driven Design (DDD) with ASP.NET Core: Practical Enterprise Implementation

1. What is Domain-Driven Design?

Domain-Driven Design (DDD) is a software design approach that focuses on understanding and modelling the business domain before designing the technical implementation.

Instead of starting with database tables, controllers, and APIs, DDD starts by understanding:

  • What business problem are we solving?
  • What are the important business concepts?
  • What business rules must always be followed?
  • What operations can users perform?
  • How do different business areas interact?

Example: E-commerce application

Consider an e-commerce application. Important business concepts include:

  • Customer
  • Product
  • Shopping Cart
  • Order
  • Payment
  • Inventory
  • Shipment

DDD models these concepts and their business rules explicitly instead of putting all business logic inside controllers or database procedures.

2. Why Do We Need DDD?

In a traditional application, business logic often becomes distributed across controllers, services, repositories, and database operations.

As the application grows, this can lead to:

  • Controllers containing too much business logic.
  • Services becoming large and difficult to maintain.
  • Business rules being duplicated across multiple places.
  • Changes in one feature affecting unrelated features.
  • Difficult unit testing.
  • Tight coupling between business logic and infrastructure.

DDD addresses these problems by organizing the application around business concepts and clearly defined boundaries.

3. Core Building Blocks of DDD

3.1 Domain

The domain is the business area that the application is designed to support.

Examples:

  • Banking domain
  • E-commerce domain
  • Healthcare domain
  • Insurance domain
  • Logistics domain

For an e-commerce application, order processing, payment, inventory, and shipping are important parts of the domain.

3.2 Subdomain

A subdomain is a smaller business area within the overall domain.

For example, an e-commerce system can contain:

Subdomain Responsibility
Catalog Products, categories, descriptions and prices.
Ordering Order creation, order validation and order status.
Inventory Stock availability and stock reservation.
Payments Payment authorization, capture and refund.
Shipping Shipment creation and delivery tracking.

3.3 Types of Subdomains

DDD classifies subdomains into three major categories.

  • Core Domain: The main business capability that differentiates the organization from competitors.
  • Supporting Subdomain: A business capability that supports the core domain but does not provide the primary competitive advantage.
  • Generic Subdomain: A common capability that many businesses need, such as authentication or standard email delivery.

Example:

Business capability Possible classification
Product recommendation engine Core
Order management Supporting or Core, depending on the business
Email notifications Generic
Authentication Generic

Classification depends on the organization's actual business strategy. It is not fixed for every application.

4. Ubiquitous Language

Ubiquitous Language means using the same business terminology across conversations, requirements, domain models, code, and documentation.

Developers and business experts should understand the same terms in the same way.

Example:

Instead of using generic names such as:

ProcessData()
UpdateStatus()
HandleRequest()

Use business-specific names:

PlaceOrder()
ConfirmPayment()
ReserveInventory()
CancelOrder()
ShipOrder()

Benefits:

  • Improves communication between developers and business teams.
  • Makes code easier to understand.
  • Reduces misunderstandings.
  • Connects business requirements directly to implementation.

5. Bounded Context

A Bounded Context is an explicit boundary within which a particular domain model and its terminology apply.

The same business term may have different meanings in different bounded contexts.

Example: Consider a Product in an e-commerce application.

  • Catalog Context: Product contains name, description, images and display price.
  • Inventory Context: Product is represented by SKU, available quantity and warehouse information.
  • Ordering Context: Product information may be represented by an order line containing product ID, quantity and price at the time of purchase.

These contexts should not be forced to share one large Product entity.

Bounded Context Architecture – SVG Diagram

E-commerce Bounded Contexts Catalog Context Product Name Description Display Price Inventory Context SKU Available Quantity Warehouse Ordering Context Order Order Lines Purchase Price Snapshot Separate Models, Clear Boundaries Each context owns its business rules and model. Integration happens through explicit contracts and messages.

6. Entities

An Entity is an object that has a unique identity and continues to be the same business object even when its properties change.

Example: An Order remains the same order even if its status changes from Pending to Confirmed.

Order Entity Example

public class Order
{
    public int Id { get; private set; }
    public string CustomerName { get; private set; }
    public string Status { get; private set; }
    public Order(string customerName)
    {
        if (string.IsNullOrWhiteSpace(customerName))
            throw new ArgumentException("Customer is required.");
        CustomerName = customerName;
        Status = "Pending";
    }
    public void Confirm()
    {
        if (Status != "Pending")
            throw new InvalidOperationException(
                "Only pending orders can be confirmed.");
        Status = "Confirmed";
    }
    public void Cancel()
    {
        if (Status == "Shipped")
            throw new InvalidOperationException(
                "Shipped orders cannot be cancelled.");
        if (Status == "Cancelled")
            throw new InvalidOperationException(
                "Order is already cancelled.");
        Status = "Cancelled";
    }
}

Notice that the properties have private setters. External code cannot freely modify the order state. It must use business methods.

7. Value Objects

A Value Object is an object defined by its values rather than by a unique identity.

Two value objects with the same values are considered equal.

Examples:

  • Money
  • Address
  • Coordinates
  • Date Range
  • Phone Number

Money Value Object Example

public sealed record Money(
    decimal Amount,
    string Currency)
{
    public Money Add(Money other)
    {
        if (Currency != other.Currency)
            throw new InvalidOperationException(
                "Currencies must match.");
        return new Money(
            Amount + other.Amount,
            Currency);
    }
}

Usage:

var price = new Money(1000, "INR");
var delivery = new Money(100, "INR");
var total = price.Add(delivery);
// Result: 1100 INR

Value objects are generally immutable and help keep validation and value-related business rules together.

8. Aggregate and Aggregate Root

An Aggregate is a group of related domain objects treated as a consistency boundary.

An Aggregate Root is the main entity through which external code accesses and modifies the aggregate.

Example: An Order aggregate may contain:

  • Order
  • OrderItem
  • ShippingAddress
  • PaymentSummary

The Order is the aggregate root. External code should modify order items through the Order rather than directly changing an OrderItem.

Aggregate Structure – SVG Diagram

Order Aggregate Order Aggregate Root Order Items Product and quantity Shipping Address Address value object Payment Summary Payment information External code changes aggregate members through Order. The aggregate root protects business invariants.

Order Aggregate Implementation

public class Order
{
    private readonly List<OrderItem> _items = new();
    public int Id { get; private set; }
    public string CustomerName { get; private set; }
    public IReadOnlyCollection<OrderItem> Items =>
        _items.AsReadOnly();
    public string Status { get; private set; } = "Pending";
    private Order()
    {
        CustomerName = string.Empty;
    }
    public Order(string customerName)
    {
        if (string.IsNullOrWhiteSpace(customerName))
            throw new ArgumentException("Customer required.");
        CustomerName = customerName;
    }
    public void AddItem(int productId, int quantity, Money price)
    {
        if (Status != "Pending")
            throw new InvalidOperationException(
                "Items can only be added to pending orders.");
        if (quantity <= 0)
            throw new ArgumentException(
                "Quantity must be greater than zero.");
        _items.Add(new OrderItem(productId, quantity, price));
    }
    public void Confirm()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException(
                "Cannot confirm an empty order.");
        Status = "Confirmed";
    }
}
public class OrderItem
{
    public int ProductId { get; private set; }
    public int Quantity { get; private set; }
    public Money UnitPrice { get; private set; }
    private OrderItem()
    {
        UnitPrice = new Money(0, "INR");
    }
    internal OrderItem(
        int productId,
        int quantity,
        Money unitPrice)
    {
        ProductId = productId;
        Quantity = quantity;
        UnitPrice = unitPrice;
    }
}

This example illustrates encapsulation and aggregate boundaries. In production, also validate product identifiers, currency consistency, total calculations, and order status transitions.

Important Aggregate Rules

  • Modify an aggregate through its root.
  • Keep aggregates as small as practical.
  • Protect business invariants inside the aggregate.
  • Use references by ID to other aggregates rather than large object graphs.
  • Prefer one transaction per aggregate modification.

9. Domain Services

A Domain Service contains domain logic that does not naturally belong to a single entity or value object.

Example: A pricing calculation involving multiple business concepts.

public class OrderPricingService
{
    public Money CalculateTotal(
        Money productTotal,
        Money deliveryCharge,
        Money discount)
    {
        if (productTotal.Currency != deliveryCharge.Currency ||
            productTotal.Currency != discount.Currency)
        {
            throw new InvalidOperationException(
                "All amounts must use the same currency.");
        }
        var total = productTotal.Amount
                  + deliveryCharge.Amount
                  - discount.Amount;
        if (total < 0)
            total = 0;
        return new Money(total, productTotal.Currency);
    }
}

Domain services should be focused on domain rules, not database access, HTTP requests, or message-broker communication.

10. Domain Events

A Domain Event represents an important business occurrence inside a domain.

Examples:

  • OrderPlaced
  • OrderConfirmed
  • PaymentReceived
  • InventoryReserved

Define a Domain Event

public interface IDomainEvent
{
    DateTime OccurredAtUtc { get; }
}
public record OrderConfirmedDomainEvent(
    int OrderId,
    DateTime OccurredAtUtc
) : IDomainEvent;

Raise a Domain Event from an Aggregate

public class Order
{
    private readonly List<IDomainEvent> _domainEvents = new();
    public int Id { get; private set; }
    public string Status { get; private set; } = "Pending";
    public IReadOnlyCollection<IDomainEvent> DomainEvents =>
        _domainEvents.AsReadOnly();
    public void Confirm()
    {
        if (Status != "Pending")
            throw new InvalidOperationException(
                "Only pending orders can be confirmed.");
        Status = "Confirmed";
        _domainEvents.Add(
            new OrderConfirmedDomainEvent(
                Id,
                DateTime.UtcNow));
    }
    public void ClearDomainEvents()
    {
        _domainEvents.Clear();
    }
}

The aggregate records the event. The application or infrastructure layer can later dispatch it to interested handlers.

11. Domain Event vs Integration Event

These two event types serve different purposes.

Domain Event Integration Event
Represents an important occurrence within a bounded context. Communicates a business occurrence to other systems or services.
Usually handled inside the application or domain boundary. Usually published through a message broker or integration mechanism.
Can use internal domain types. Should use stable, versioned message contracts.
Example: OrderConfirmedDomainEvent. Example: OrderConfirmedIntegrationEvent.

A domain event should not automatically be sent to an external broker. The application layer can translate it into an integration event after the relevant transaction succeeds.

12. Repositories

A Repository provides an abstraction for retrieving and persisting aggregate roots.

It separates domain and application code from the underlying persistence implementation.

Repository Interface

public interface IOrderRepository
{
    Task<Order?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken);
    Task AddAsync(
        Order order,
        CancellationToken cancellationToken);
}

EF Core Repository Implementation

public class OrderRepository : IOrderRepository
{
    private readonly AppDbContext _context;
    public OrderRepository(AppDbContext context)
    {
        _context = context;
    }
    public async Task<Order?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken)
    {
        return await _context.Orders
            .Include(x => x.Items)
            .FirstOrDefaultAsync(
                x => x.Id == id,
                cancellationToken);
    }
    public async Task AddAsync(
        Order order,
        CancellationToken cancellationToken)
    {
        await _context.Orders.AddAsync(
            order,
            cancellationToken);
    }
}

In this example, SaveChangesAsync is not called inside the repository. The application can coordinate persistence through a Unit of Work or directly through the scoped DbContext.

13. Unit of Work

A Unit of Work coordinates changes made during one business operation and commits them together.

EF Core's DbContext already provides Unit of Work behavior through change tracking and SaveChanges.

public interface IUnitOfWork
{
    Task<int> SaveChangesAsync(
        CancellationToken cancellationToken);
}
public class AppDbContext : DbContext, IUnitOfWork
{
    public AppDbContext(
        DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    public DbSet<Order> Orders => Set<Order>();
    public Task<int> SaveChangesAsync(
        CancellationToken cancellationToken)
    {
        return base.SaveChangesAsync(cancellationToken);
    }
}

14. DDD Layered Architecture

A common enterprise DDD implementation uses four logical layers.

  1. Domain Layer: Entities, value objects, aggregates, domain services, domain events and business rules.
  2. Application Layer: Use cases, commands, queries, handlers, interfaces and application orchestration.
  3. Infrastructure Layer: EF Core, repositories, database access, external APIs, messaging and file storage.
  4. Presentation Layer: ASP.NET Core controllers, endpoints, authentication and HTTP request/response handling.

DDD Layered Architecture – SVG Diagram

DDD Layered Architecture Presentation Layer ASP.NET Core API / Controllers / Endpoints Application Layer Use Cases / Commands / Queries / Handlers Application Interfaces Domain Layer Entities / Value Objects / Aggregates Domain Services / Domain Events / Rules Infrastructure Layer EF Core / Repositories / Messaging External Services / Storage External Systems SQL Server / RabbitMQ / Payment API Email / Other Services Core business logic remains independent of infrastructure details.

15. Dependency Inversion Principle in DDD

The Domain Layer should not depend on EF Core, SQL Server, RabbitMQ, or other infrastructure technologies.

Instead:

  • The Domain Layer contains business rules.
  • The Application Layer defines interfaces required by use cases.
  • The Infrastructure Layer implements those interfaces.
  • Dependency Injection connects the implementations at runtime.

For example:

Application Layer:
    IOrderRepository
Infrastructure Layer:
    OrderRepository : IOrderRepository
ASP.NET Core Dependency Injection:
    IOrderRepository -> OrderRepository

This makes business logic easier to test and reduces coupling to infrastructure.

16. Practical Enterprise Project Structure

A common solution structure for an ASP.NET Core DDD application is:

EnterpriseECommerce/
|
+-- src/
|   |
|   +-- EnterpriseECommerce.Api/
|   |   +-- Controllers/
|   |   +-- Middleware/
|   |   +-- Extensions/
|   |   +-- Program.cs
|   |
|   +-- EnterpriseECommerce.Application/
|   |   +-- Orders/
|   |   |   +-- Commands/
|   |   |   |   +-- CreateOrder/
|   |   |   |   +-- CancelOrder/
|   |   |   +-- Queries/
|   |   |   |   +-- GetOrder/
|   |   |   +-- DTOs/
|   |   +-- Abstractions/
|   |   +-- Behaviors/
|   |
|   +-- EnterpriseECommerce.Domain/
|   |   +-- Orders/
|   |   |   +-- Order.cs
|   |   |   +-- OrderItem.cs
|   |   |   +-- OrderStatus.cs
|   |   |   +-- Events/
|   |   +-- Common/
|   |       +-- Entity.cs
|   |       +-- ValueObject.cs
|   |       +-- IDomainEvent.cs
|   |
|   +-- EnterpriseECommerce.Infrastructure/
|   |   +-- Persistence/
|   |   |   +-- AppDbContext.cs
|   |   |   +-- Configurations/
|   |   |   +-- Repositories/
|   |   +-- Messaging/
|   |   +-- ExternalServices/
|   |
|   +-- EnterpriseECommerce.Contracts/
|       +-- Events/
|       +-- IntegrationMessages/
|
+-- tests/
    +-- EnterpriseECommerce.Domain.Tests/
    +-- EnterpriseECommerce.Application.Tests/
    +-- EnterpriseECommerce.Infrastructure.Tests/
    +-- EnterpriseECommerce.Api.Tests/

The Contracts project is optional. It is useful when integration message contracts need to be shared across independently deployed services. Avoid making the Domain project depend on it.

17. Practical Implementation: Create Order Use Case

Let's implement a simplified Create Order use case using DDD principles.

Step 1: Create the Domain Entity

public class Order
{
    private readonly List<OrderItem> _items = new();
    public int Id { get; private set; }
    public string CustomerName { get; private set; }
    public string Status { get; private set; }
    public IReadOnlyCollection<OrderItem> Items =>
        _items.AsReadOnly();
    private Order()
    {
        CustomerName = string.Empty;
        Status = "Pending";
    }
    public Order(string customerName)
    {
        if (string.IsNullOrWhiteSpace(customerName))
            throw new ArgumentException("Customer name required.");
        CustomerName = customerName;
        Status = "Pending";
    }
    public void AddItem(
        int productId,
        int quantity,
        Money price)
    {
        if (Status != "Pending")
            throw new InvalidOperationException(
                "Cannot modify a confirmed order.");
        if (productId <= 0 || quantity <= 0)
            throw new ArgumentException("Invalid order item.");
        _items.Add(new OrderItem(productId, quantity, price));
    }
    public void Confirm()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException(
                "Order must contain at least one item.");
        Status = "Confirmed";
    }
}

Step 2: Create the Repository Interface

public interface IOrderRepository
{
    Task AddAsync(
        Order order,
        CancellationToken cancellationToken);
}

Step 3: Create the Application Command

using MediatR;
public record CreateOrderCommand(
    string CustomerName,
    List<CreateOrderItemRequest> Items
) : IRequest<int>;
public record CreateOrderItemRequest(
    int ProductId,
    int Quantity,
    decimal UnitPrice
);

Step 4: Create the Command Handler

public class CreateOrderHandler
    : IRequestHandler<CreateOrderCommand, int>
{
    private readonly IOrderRepository _repository;
    private readonly IUnitOfWork _unitOfWork;
    public CreateOrderHandler(
        IOrderRepository repository,
        IUnitOfWork unitOfWork)
    {
        _repository = repository;
        _unitOfWork = unitOfWork;
    }
    public async Task<int> Handle(
        CreateOrderCommand request,
        CancellationToken cancellationToken)
    {
        var order = new Order(request.CustomerName);
        foreach (var item in request.Items)
        {
            order.AddItem(
                item.ProductId,
                item.Quantity,
                new Money(item.UnitPrice, "INR"));
        }
        await _repository.AddAsync(
            order,
            cancellationToken);
        await _unitOfWork.SaveChangesAsync(
            cancellationToken);
        return order.Id;
    }
}

Step 5: Configure EF Core

public class AppDbContext : DbContext, IUnitOfWork
{
    public AppDbContext(
        DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    public DbSet<Order> Orders => Set<Order>();
    protected override void OnModelCreating(
        ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>(builder =>
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.CustomerName)
                .HasMaxLength(150)
                .IsRequired();
            builder.Property(x => x.Status)
                .HasMaxLength(30)
                .IsRequired();
            builder.HasMany<OrderItem>("_items")
                .WithOne()
                .HasForeignKey("OrderId")
                .OnDelete(DeleteBehavior.Cascade);
            builder.Navigation("_items")
                .UsePropertyAccessMode(
                    PropertyAccessMode.Field);
        });
        modelBuilder.Entity<OrderItem>(builder =>
        {
            builder.HasKey("Id");
            builder.Property<int>("Id")
                .ValueGeneratedOnAdd();
            builder.OwnsOne(x => x.UnitPrice, money =>
            {
                money.Property(x => x.Amount)
                    .HasColumnName("UnitPriceAmount");
                money.Property(x => x.Currency)
                    .HasColumnName("Currency")
                    .HasMaxLength(3);
            });
        });
    }
}

This is an illustrative EF Core mapping. A production mapping should explicitly configure all required fields, constraints, indexes, owned types, and private constructors according to the selected EF Core version and database provider.

Step 6: Implement the Repository

public class OrderRepository : IOrderRepository
{
    private readonly AppDbContext _context;
    public OrderRepository(AppDbContext context)
    {
        _context = context;
    }
    public async Task AddAsync(
        Order order,
        CancellationToken cancellationToken)
    {
        await _context.Orders.AddAsync(
            order,
            cancellationToken);
    }
}

Step 7: Register Dependencies

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IUnitOfWork>(
    services => services.GetRequiredService<AppDbContext>());
builder.Services.AddMediatR(configuration =>
    configuration.RegisterServicesFromAssembly(
        typeof(CreateOrderHandler).Assembly));
var app = builder.Build();
app.MapControllers();
app.Run();

18. DDD and Clean Architecture

DDD and Clean Architecture are related, but they are not the same thing.

  • DDD: Focuses on modelling complex business domains and defining business boundaries.
  • Clean Architecture: Focuses on dependency direction and separating business rules from technical details.

They can be combined. DDD provides the domain model, while Clean Architecture provides a structure for organizing dependencies and layers.

19. DDD and Microservices

Bounded Contexts can help identify possible microservice boundaries.

For example:

E-commerce System
       |
       +-- Catalog Service
       |
       +-- Ordering Service
       |
       +-- Inventory Service
       |
       +-- Payment Service
       |
       +-- Shipping Service

Each service may own its own domain model and database.

However, a bounded context does not automatically need to become a separate microservice. A modular monolith can contain multiple bounded contexts within one deployable application.

Modular Monolith vs Microservices

Aspect Modular Monolith Microservices
Deployment One deployable application Independently deployable services
Boundaries Logical modules Network-separated services
Communication In-process interfaces or messaging HTTP, gRPC, messaging
Database Can share one database with controlled ownership Each service should own its data
Operational complexity Usually lower Usually higher

20. DDD Best Practices for Enterprise Applications

  • Understand business requirements before designing entities and tables.
  • Work with domain experts to establish ubiquitous language.
  • Identify bounded contexts based on business capabilities.
  • Keep aggregates small and protect invariants inside aggregate roots.
  • Use value objects for concepts defined by their values.
  • Keep controllers thin.
  • Keep domain logic independent of EF Core and external systems.
  • Use repositories for aggregate persistence rather than creating generic repositories for every table.
  • Use domain events for important internal business occurrences.
  • Use integration events for communication across service boundaries.
  • Use the Outbox Pattern when reliable event publication is required.
  • Use optimistic concurrency where concurrent updates are possible.
  • Test business rules independently from the database.
  • Do not introduce microservices solely because the application uses DDD.

21. Common DDD Mistakes

  • Anemic Domain Model: Entities contain only properties while all business rules are placed in external services.
  • Oversized Aggregates: Too many objects are included in one aggregate, creating unnecessary transaction and concurrency problems.
  • Database-First Modelling: Designing entities only around database tables instead of business concepts.
  • Generic Repository Everywhere: Creating unnecessary abstractions for every table instead of focusing on aggregate roots and use cases.
  • Shared Domain Model Across Contexts: Forcing multiple bounded contexts to use one model even when their business meanings differ.
  • Domain Layer Depending on Infrastructure: Allowing domain entities to directly call repositories, databases, or message brokers.
  • Unnecessary Microservices: Splitting every bounded context into a separate service without considering operational costs.

22. Unit Testing Domain Logic

One important advantage of DDD is that business rules can be tested without starting the database or ASP.NET Core application.

Example using xUnit:

public class OrderTests
{
    [Fact]
    public void Confirm_ShouldChangeStatus_WhenOrderHasItems()
    {
        var order = new Order("Customer A");
        order.AddItem(
            100,
            2,
            new Money(500, "INR"));
        order.Confirm();
        Assert.Equal("Confirmed", order.Status);
    }
    [Fact]
    public void Confirm_ShouldFail_WhenOrderIsEmpty()
    {
        var order = new Order("Customer A");
        Assert.Throws<InvalidOperationException>(
            () => order.Confirm());
    }
}

These tests verify business behavior directly without relying on SQL Server or an HTTP API.

23. DDD vs Traditional Layered Architecture

Traditional Layered Approach DDD Approach
Often starts from database entities. Starts from business concepts and rules.
Business logic may be spread across services. Business rules are modelled in the domain.
Entities may expose public setters. Aggregates control state changes.
Generic data models may be shared everywhere. Bounded contexts have models suited to their responsibilities.
Simple to implement for straightforward CRUD. Useful for complex business domains.

24. Enterprise DDD Interview Questions and Answers

Q1. What is Domain-Driven Design?

DDD is a software design approach that focuses on understanding and modelling the business domain, its rules, and its terminology.

Q2. What is a bounded context?

A bounded context is a boundary within which a specific domain model and its language are consistently defined.

Q3. What is ubiquitous language?

It is a shared business vocabulary used consistently by domain experts and developers in discussions, documentation, and code.

Q4. What is the difference between an entity and a value object?

An entity is identified by its identity, while a value object is identified by its values and is generally immutable.

Q5. What is an aggregate?

An aggregate is a group of related domain objects that form a consistency boundary.

Q6. What is an aggregate root?

The aggregate root is the main entity through which an aggregate is accessed and modified.

Q7. Why should aggregates be small?

Small aggregates reduce locking, concurrency conflicts, transaction complexity, and unnecessary object loading.

Q8. What is a domain service?

A domain service contains business logic that does not naturally belong to a particular entity or value object.

Q9. What is a repository in DDD?

A repository abstracts the persistence of aggregate roots and provides a collection-like interface for retrieving and storing them.

Q10. What is a domain event?

A domain event represents an important business occurrence inside a bounded context.

Q11. What is the difference between domain events and integration events?

Domain events represent internal domain occurrences. Integration events communicate relevant business occurrences to other services or external systems.

Q12. What is the difference between DDD and Clean Architecture?

DDD focuses on business modelling. Clean Architecture focuses on separation of concerns and dependency direction. They can be used together.

Q13. Does DDD require microservices?

No. DDD can be implemented in a monolith, modular monolith, or microservices architecture.

Q14. What is an anemic domain model?

It is a model where entities mainly contain data while business rules are implemented outside them, often in service classes.

Q15. What is the difference between a core and generic subdomain?

A core subdomain represents a key competitive business capability. A generic subdomain provides common functionality that is not a unique differentiator.

Q16. How do you implement DDD in ASP.NET Core?

Separate the application into Domain, Application, Infrastructure, and Presentation projects. Implement entities, value objects, aggregates, repositories, domain events, and use cases. Use dependency injection to connect abstractions to infrastructure implementations.

Q17. How does EF Core support DDD?

EF Core supports private constructors, field-backed navigation properties, owned entity types, value conversions, explicit mappings, and optimistic concurrency.

Q18. What is the difference between a bounded context and a microservice?

A bounded context is a business model boundary. A microservice is an independently deployable software unit. A bounded context can be implemented as a module within a monolith or as a separate service.

Q19. What is the purpose of the Outbox Pattern?

It ensures that a database change and the event record describing that change are committed together. A background worker publishes the event afterward.

Q20. How do you test DDD applications?

Test domain rules with unit tests, application use cases with handler tests, persistence mappings with integration tests, and HTTP behavior with API tests.

25. Final Summary

  • Domain: The business problem area.
  • Subdomain: A smaller business capability.
  • Ubiquitous Language: Shared business terminology.
  • Bounded Context: A boundary for a particular domain model.
  • Entity: An object with a unique identity.
  • Value Object: An object defined by its values.
  • Aggregate: A consistency boundary around related domain objects.
  • Aggregate Root: The entry point for modifying an aggregate.
  • Domain Service: Business logic that does not naturally belong to an entity.
  • Domain Event: An important internal business occurrence.
  • Repository: An abstraction for aggregate persistence.
  • Unit of Work: Coordinates persistence changes in a business operation.

Key takeaway: DDD is not primarily about creating more projects, classes, or interfaces. It is about making the software model accurately represent the business, protecting important business rules, and keeping complex enterprise applications maintainable as they grow.

🔙
CQRS and Event-Driven Architecture :👈 👉:Distributed Transactions: Saga Pattern and Outbox Pattern