Skip to content

Clean Architecture and DDD

Vitreous works the same in a solution split into layers as in a single project. The source generator runs in the host project only, finds the handlers in every layer at build time, and the layers themselves reference nothing but the core Vitreous package. This page walks through the sample in samples/Vitreous.Sample.DDD*, four projects that build the orders API from Build your first feature around an Order aggregate.

To start your own solution in these layers, use the vitreous-clean template.

  • Directorysamples/
    • DirectoryVitreous.Sample.DDD.Domain/ the model: aggregate, invariants, domain events
      • IHasDomainEvents.cs
      • DirectoryOrders/
        • Order.cs
        • OrderCreated.cs
    • DirectoryVitreous.Sample.DDD.Application/ use cases: messages, handlers, validators
      • DirectoryAbstractions/
        • IAppDbContext.cs
      • DirectoryOrders/
        • DirectoryCommands/
          • CreateOrderCommand.cs
          • DeleteOrderCommand.cs
        • DirectoryQueries/
          • OrderQueries.cs
        • DirectoryNotifications/
          • LogOrderCreatedHandler.cs
    • DirectoryVitreous.Sample.DDD.Infrastructure/ implementations: EF Core, email
      • DependencyInjection.cs
      • DirectoryPersistence/
        • AppDbContext.cs
      • DirectoryOrders/
        • DirectoryNotifications/
          • SendConfirmationEmailHandler.cs
    • DirectoryVitreous.Sample.DDD/ the host: endpoints, DI, cross-cutting behaviors
      • Program.cs
      • DirectoryBehaviors/
        • LoggingBehavior.cs
Project Contains References
Vitreous.Sample.DDD.Domain The Order aggregate and its invariants, the OrderCreated domain event Vitreous only
Vitreous.Sample.DDD.Application Commands, queries and their handlers, FluentValidation validators, a domain event handler, the IAppDbContext the handlers use Domain, Vitreous, FluentValidation, Microsoft.EntityFrameworkCore
Vitreous.Sample.DDD.Infrastructure AppDbContext, which implements IAppDbContext with EF Core and publishes domain events after saving; the confirmation email handler Application (and Domain through it), Microsoft.EntityFrameworkCore.Sqlite
Vitreous.Sample.DDD (host) Program.cs, the endpoints, the logging behavior, DI registration All three, plus Vitreous.SourceGeneration, Vitreous.DevUI, Vitreous.FluentValidation

Dependencies point inwards, towards the domain:

Vitreous.Sample.DDD (host)
└── Vitreous.Sample.DDD.Infrastructure
└── Vitreous.Sample.DDD.Application
└── Vitreous.Sample.DDD.Domain
└── Vitreous (abstractions only)

The domain depends on nothing but Vitreous, not even EF Core. Application declares the data its handlers need as IAppDbContext, and Infrastructure implements it. Vitreous fits this rule because messages, handlers and events are plain types that implement interfaces from the core package. Nothing in the inner layers registers itself, scans assemblies or knows about the host.

The domain references Vitreous for its abstractions only: invariants return a Result or an Error, and domain events implement INotification. It has no handlers, no DI registration, no Vitreous behaviors and no EF Core.

Order.cs has a private constructor, so the only way to get an Order is Order.Create, which enforces the invariants. A broken invariant is an expected failure, so it is returned as an Error, not thrown:

public sealed class Order
{
public const int MaxQuantity = 100;
private readonly List<INotification> _domainEvents = [];
private Order(Guid id, string customerName, string product, int quantity, DateTimeOffset createdAt) { ... }
public static Result<Order> Create(string customerName, string product, int quantity, DateTimeOffset createdAt)
{
var failures = new Dictionary<string, string[]>();
if (string.IsNullOrWhiteSpace(customerName))
failures[nameof(CustomerName)] = ["CustomerName is required."];
if (string.IsNullOrWhiteSpace(product))
failures[nameof(Product)] = ["Product is required."];
if (quantity is <= 0 or > MaxQuantity)
failures[nameof(Quantity)] = [$"Quantity must be between 1 and {MaxQuantity}."];
if (failures.Count > 0)
return Error.Validation("The order is invalid.", failures);
var order = new Order(Guid.NewGuid(), customerName, product, quantity, createdAt);
order._domainEvents.Add(new OrderCreated(order.Id, order.CustomerName, order.Product));
return order;
}
public IReadOnlyList<INotification> DequeueDomainEvents() { ... } // returns the events and clears them
}

The failures use the same shape as FluentValidation’s, so the endpoint turns both into the same 400 validation problem.

When something happens that other parts of the system care about, the aggregate records a domain event. OrderCreated.cs is a past-tense record that implements INotification, so any number of handlers in any layer can react to it:

public sealed record OrderCreated(Guid OrderId, string CustomerName, string Product) : INotification;

The aggregate only records the event. It doesn’t publish it, because it has no IPublisher and the order isn’t saved yet.

Order implements IHasDomainEvents, a one-method interface the domain declares, so Infrastructure can collect the events of any entity it saves without knowing its type:

public interface IHasDomainEvents
{
IReadOnlyList<INotification> DequeueDomainEvents(); // returns the events and clears them
}

Each use case is a message and its handler, side by side in one file. CreateOrderCommand.cs holds the command, its validator and its handler. The handler coordinates: it asks the domain for an order and adds it to the database. It holds no business rules itself.

public sealed record CreateOrderCommand(string CustomerName, string Product, int Quantity) : ICommand<Guid>;
public sealed class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand>
{
public CreateOrderCommandValidator()
{
RuleFor(c => c.CustomerName).NotEmpty().WithMessage("CustomerName is required.");
RuleFor(c => c.Product).NotEmpty().WithMessage("Product is required.");
RuleFor(c => c.Quantity).GreaterThan(0).WithMessage("Quantity must be greater than zero.");
}
}
public sealed class CreateOrderCommandHandler : ICommandHandler<CreateOrderCommand, Guid>
{
// IAppDbContext and ILogger are injected through the constructor.
public async ValueTask<Result<Guid>> Handle(CreateOrderCommand command, CancellationToken ct = default)
{
var created = Order.Create(command.CustomerName, command.Product, command.Quantity, DateTimeOffset.UtcNow);
if (created.IsFailure)
return created.Error;
_db.Orders.Add(created.Value);
await _db.SaveChangesAsync(ct); // saves, then publishes OrderCreated
return created.Value.Id;
}
}

The handlers use EF Core directly. A DbContext already is a unit of work, and each DbSet a repository, so the sample adds no repository layer on top. Queries project straight to DTOs, and a delete is one statement:

var order = await _db.Orders
.AsNoTracking()
.Where(o => o.Id == query.OrderId)
.Select(o => new OrderDto(o.Id, o.CustomerName, o.Product, o.Quantity, o.CreatedAt))
.FirstOrDefaultAsync(ct);
var deleted = await _db.Orders.Where(o => o.Id == command.OrderId).ExecuteDeleteAsync(ct);

To keep Application independent of Infrastructure and of the database provider, the handlers depend on IAppDbContext, which Application declares, rather than on the concrete context:

public interface IAppDbContext
{
DbSet<Order> Orders { get; }
/// <summary>Saves the changes, then publishes the domain events of the saved entities.</summary>
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

Application references the Microsoft.EntityFrameworkCore package for DbSet and the query operators, but no provider.

The validator and the aggregate both check the order, for different reasons:

  • The validator checks the shape of the input before the handler runs, through AddVitreousValidation(). It is the fast, friendly first line, and it belongs to this use case.
  • The aggregate enforces the rules that must hold whatever the caller: another use case, a background job or a test. MaxQuantity is a business rule that only the domain knows about.

So {"quantity": 0} is stopped by the validator, and {"quantity": 150} passes the validator and is stopped by Order.Create. Both return 400 with {"errors": {"Quantity": [...]}}.

The validators live in Application, next to their commands. The host registers them by pointing at any type in that assembly:

builder.Services.AddVitreousValidation();
builder.Services.AddValidatorsFromAssemblyContaining<CreateOrderCommand>();

AppDbContext.cs implements IAppDbContext. It maps Order without the domain knowing about EF: the aggregate’s private constructor and get-only properties are mapped in OnModelCreating, and EF binds the constructor’s parameters by name.

It also publishes domain events. SaveChangesAsync takes the events of every tracked IHasDomainEvents entity before saving, and publishes them through IPublisher only once the save has succeeded, so a handler never sees an order that wasn’t stored:

public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken ct = default)
{
var domainEvents = ChangeTracker.Entries<IHasDomainEvents>()
.SelectMany(e => e.Entity.DequeueDomainEvents())
.ToList();
var saved = await base.SaveChangesAsync(acceptAllChangesOnSuccess, ct);
foreach (var domainEvent in domainEvents)
await publisher.Publish(domainEvent, ct);
return saved;
}

Each event is typed INotification here. Publish dispatches on its runtime type, so an OrderCreated reaches the OrderCreated handlers. See Which handlers a notification reaches.

DependencyInjection.cs registers the context, on a SQLite in-memory database so the sample needs no server or file, and maps IAppDbContext to it. The host only calls AddInfrastructure():

public static IServiceCollection AddInfrastructure(this IServiceCollection services)
{
// ... open the connection that keeps the in-memory database alive ...
services.AddDbContext<AppDbContext>(o => o.UseSqlite(connectionString));
services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
return services;
}

AppDbContext is scoped, like the handlers and IPublisher, so each request gets its own. In a real app, swap UseSqlite for your provider and create the schema with migrations instead of EnsureCreated.

Infrastructure also handles OrderCreated, in SendConfirmationEmailHandler.cs, next to LogOrderCreatedHandler in Application. Neither is registered by hand: the generator finds both. Handlers run one after another by default; set NotificationPublishStrategy.Parallel to run them concurrently. See Notifications.

Install Vitreous.SourceGeneration on the project that calls AddVitreousHandlers(), and nowhere else. The sample references it as a project analyzer, from Vitreous.Sample.DDD.csproj:

<ProjectReference Include="..\..\src\Vitreous.SourceGeneration\Vitreous.SourceGeneration.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />

From NuGet, the same is dotnet add package Vitreous.SourceGeneration in the host project. The package is a development dependency, so it adds PrivateAssets="all" and never flows to projects that reference the host.

The generator runs two discovery passes at build time:

  1. The host’s own source. Handlers declared in the host, which in the sample is none, and the open-generic behaviors such as LoggingBehavior<,>.
  2. Every referenced assembly that references Vitreous. This picks up the commands, queries and handlers in Application, and SendConfirmationEmailHandler in Infrastructure. Domain is scanned too, but holds no handlers.

So the composition root is short, with no assembly list to keep up to date as layers are added. From Program.cs:

builder.Services.AddVitreousHandlers();
builder.Services.AddVitreousBehavior(typeof(LoggingBehavior<,>), ServiceLifetime.Singleton);
builder.Services.AddVitreousValidation();
builder.Services.AddValidatorsFromAssemblyContaining<CreateOrderCommand>();
builder.Services.AddInfrastructure();
var app = builder.Build();
app.Services.EnsureDatabaseCreated();

A command in Application with no handler anywhere in the solution is a VIT001 warning when the host builds, and two handlers for it are a VIT002 error. See Diagnostics.

The endpoints only translate HTTP to messages and Results to responses. Validation failures from the validator and from the aggregate both carry Extensions["failures"]:

app.MapPost("/orders", async (CreateOrderRequest req, ISender sender, CancellationToken ct) =>
{
var result = await sender.Send(new CreateOrderCommand(req.CustomerName, req.Product, req.Quantity), ct);
if (result.IsFailure)
return result.Error.Extensions?.GetValueOrDefault("failures") is IReadOnlyDictionary<string, string[]> failures
? Results.ValidationProblem(failures)
: Results.BadRequest(new { error = result.Error.Code, message = result.Error.Message });
return Results.Created($"/orders/{result.Value}", new { id = result.Value });
});

LoggingBehavior.cs is an open-generic pipeline behavior in the host. It wraps every command and query from every layer, including void commands such as DeleteOrderCommand, whose TResult is Unit. Behaviors belong wherever the concern belongs: logging and authorization often sit in the host, while a behavior that enforces an application policy can live in Application. The generator finds open-generic behaviors in either. See Pipeline behaviors.

Terminal window
dotnet run --project samples/Vitreous.Sample.DDD

The API listens on http://localhost:5096, with its orders in a SQLite in-memory database that starts empty on every run. In Development it also serves the Scalar API reference at /scalar/v1 and the Developer UI at /vitreous.

Terminal window
curl -X POST http://localhost:5096/orders -H 'Content-Type: application/json' \
-d '{"customerName":"Ada","product":"Widget","quantity":2}'
# 201 {"id":"..."} — the log shows both [Application] and [Infrastructure] handling OrderCreated
curl -X POST http://localhost:5096/orders -H 'Content-Type: application/json' \
-d '{"customerName":"Ada","product":"Widget","quantity":150}'
# 400 {"title":"One or more validation errors occurred.","errors":{"Quantity":["Quantity must be between 1 and 100."]},...}

In the Developer UI, the first request shows the command, the OrderCreated notification and both of its handlers, from two different projects. The /showcase/fail/* endpoints return each kind of Error, so you can see how failures look.

Because Program is declared public partial, an integration test can host the whole app with WebApplicationFactory<Program>.