Build your first feature
This tutorial builds a small orders API from an empty project: a command that creates an order, a query that reads it back, a pipeline behavior that logs every dispatch, and the endpoints that send them. The code is adapted from the layered sample in samples/Vitreous.Sample.DDD*, squeezed into one project. The Clean Architecture walkthrough shows the same feature split into Domain, Application, Infrastructure and host layers.
You need the .NET 8 SDK or later.
-
Create the project and install Vitreous.
Terminal window dotnet new web -n Orderscd Ordersdotnet add package Vitreousdotnet add package Vitreous.SourceGenerationdotnet add package Microsoft.EntityFrameworkCore.SqliteVitreous.SourceGenerationruns at build time only. It generatesAddVitreousHandlers()and the dispatcher, and adds nothing to your app at runtime. EF Core with SQLite stores the orders in a local file, so there’s no database server to set up. -
Add an order and a DbContext. Create
Orders/Order.cs. The handlers will use theDbContextdirectly: it already is a unit of work, and eachDbSeta repository, so there’s no extra layer. The order is simplified from the sample’sOrder.csaggregate.Orders/Order.cs using Microsoft.EntityFrameworkCore;namespace Orders;public sealed record Order(Guid Id, string CustomerName, string Product, int Quantity, DateTimeOffset CreatedAt);public sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options) : DbContext(options){public DbSet<Order> Orders => Set<Order>();} -
Write the command and its handler. A command changes state and has exactly one handler.
ICommand<Guid>says this one returns the new order’s ID. CreateOrders/CreateOrder.cs(from the sample’sCreateOrderCommand.cs):Orders/CreateOrder.cs using Vitreous;using Vitreous.Abstractions;namespace Orders;public sealed record CreateOrderCommand(string CustomerName, string Product, int Quantity) : ICommand<Guid>;public sealed class CreateOrderCommandHandler(OrdersDbContext db) : ICommandHandler<CreateOrderCommand, Guid>{public async ValueTask<Result<Guid>> Handle(CreateOrderCommand command, CancellationToken ct = default){if (string.IsNullOrWhiteSpace(command.CustomerName))return Error.Validation("CustomerName is required.");var order = new Order(Guid.NewGuid(), command.CustomerName, command.Product, command.Quantity, DateTimeOffset.UtcNow);db.Orders.Add(order);await db.SaveChangesAsync(ct);return order.Id; // Guid converts to Result<Guid> implicitly}}The handler returns an
Errorfor an expected failure instead of throwing. The caller gets aResult<Guid>that is either the ID or the error, never both. See Results and errors. -
Write the query and its handler. A query only reads. Create
Orders/GetOrder.cs(from the sample’sOrderQueries.cs):Orders/GetOrder.cs using Vitreous;using Vitreous.Abstractions;namespace Orders;public sealed record OrderDto(Guid Id, string CustomerName, string Product, int Quantity, DateTimeOffset CreatedAt);public sealed record GetOrderQuery(Guid OrderId) : IQuery<OrderDto>;public sealed class GetOrderQueryHandler(OrdersDbContext db) : IQueryHandler<GetOrderQuery, OrderDto>{public async ValueTask<Result<OrderDto>> Handle(GetOrderQuery query, CancellationToken ct = default){var order = await db.Orders.FindAsync([query.OrderId], ct);if (order is null)return Error.NotFound($"Order '{query.OrderId}' not found.");return new OrderDto(order.Id, order.CustomerName, order.Product, order.Quantity, order.CreatedAt);}}Build now with
dotnet build. If you delete a handler, the build warns withVIT001, because a message has no handler. Two handlers for the same message are aVIT002error. See Diagnostics. -
Add a pipeline behavior. A behavior wraps every dispatch, like middleware. This one logs each message and how long it took. Create
LoggingBehavior.cs(from the sample’sLoggingBehavior.cs):LoggingBehavior.cs using System.Diagnostics;using Vitreous;using Vitreous.Abstractions;namespace Orders;public sealed class LoggingBehavior<TMessage, TResult>(ILogger<LoggingBehavior<TMessage, TResult>> logger): IPipelineBehavior<TMessage, TResult>{public async ValueTask<Result<TResult>> Handle(TMessage message,MessageHandlerDelegate<TMessage, TResult> next,CancellationToken ct = default){var sw = Stopwatch.StartNew();var result = await next(message, ct);if (result.IsSuccess)logger.LogInformation("{MessageType} succeeded in {ElapsedMs}ms", typeof(TMessage).Name, sw.ElapsedMilliseconds);elselogger.LogWarning("{MessageType} failed in {ElapsedMs}ms: [{Code}] {Message}",typeof(TMessage).Name, sw.ElapsedMilliseconds, result.Error.Code, result.Error.Message);return result;}}One open-generic behavior covers every command and query. See Pipeline behaviors.
-
Register everything and map the endpoints. Replace
Program.cs:Program.cs using Microsoft.EntityFrameworkCore;using Orders;using Vitreous;using Vitreous.Abstractions;var builder = WebApplication.CreateBuilder(args);builder.Services.AddVitreousHandlers(); // generated: every handler in the projectbuilder.Services.AddVitreousBehavior(typeof(LoggingBehavior<,>)); // after AddVitreousHandlers()builder.Services.AddDbContext<OrdersDbContext>(o => o.UseSqlite("Data Source=orders.db"));var app = builder.Build();// Creates orders.db and its table on first run. Use migrations in a real app.using (var scope = app.Services.CreateScope())scope.ServiceProvider.GetRequiredService<OrdersDbContext>().Database.EnsureCreated();app.MapPost("/orders", async (CreateOrderCommand command, ISender sender, CancellationToken ct) =>(await sender.Send(command, ct)).Match(id => Results.Created($"/orders/{id}", new { id }),error => Results.BadRequest(new { error.Code, error.Message })));app.MapGet("/orders/{id:guid}", async (Guid id, ISender sender, CancellationToken ct) =>(await sender.Send(new GetOrderQuery(id), ct)).Match(order => Results.Ok(order),error => Results.NotFound(new { error.Code, error.Message })));app.Run();Handlers are scoped by default, like
AddDbContext, so each request gets its ownOrdersDbContext. Endpoints takeISender, which dispatches commands and queries.Matchturns theResultinto a response: one function for success and one for the error. -
Run it.
Terminal window dotnet run --urls http://localhost:5000In a second terminal, create an order, then read it back with the ID from the response:
Terminal window curl -i -X POST http://localhost:5000/orders \-H 'Content-Type: application/json' \-d '{"customerName":"Ada","product":"Widget","quantity":2}'# HTTP/1.1 201 Created# Location: /orders/3f2c...# {"id":"3f2c..."}curl http://localhost:5000/orders/3f2c...# {"id":"3f2c...","customerName":"Ada","product":"Widget","quantity":2,"createdAt":"..."}An empty customer name returns
400with{"code":"VALIDATION",...}, and an unknown ID returns404with{"code":"NOT_FOUND",...}. The console shows a line fromLoggingBehaviorfor every request.
Next steps
Section titled “Next steps”- Validation: replace the
ifin the handler with a FluentValidation validator that runs before it. - Caching: make
GetOrderQuerycacheable and invalidate it from the command. - Developer UI: watch each dispatch, with its input, output and logs, in the browser.
- Clean Architecture and DDD: split the feature into Domain, Application, Infrastructure and host projects, with an aggregate that raises domain events.