Skip to content

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.

  1. Create the project and install Vitreous.

    Terminal window
    dotnet new web -n Orders
    cd Orders
    dotnet add package Vitreous
    dotnet add package Vitreous.SourceGeneration
    dotnet add package Microsoft.EntityFrameworkCore.Sqlite

    Vitreous.SourceGeneration runs at build time only. It generates AddVitreousHandlers() 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.

  2. Add an order and a DbContext. Create Orders/Order.cs. The handlers will use the DbContext directly: it already is a unit of work, and each DbSet a repository, so there’s no extra layer. The order is simplified from the sample’s Order.cs aggregate.

    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>();
    }
  3. 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. Create Orders/CreateOrder.cs (from the sample’s CreateOrderCommand.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 Error for an expected failure instead of throwing. The caller gets a Result<Guid> that is either the ID or the error, never both. See Results and errors.

  4. Write the query and its handler. A query only reads. Create Orders/GetOrder.cs (from the sample’s OrderQueries.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 with VIT001, because a message has no handler. Two handlers for the same message are a VIT002 error. See Diagnostics.

  5. 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’s LoggingBehavior.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);
    else
    logger.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.

  6. 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 project
    builder.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 own OrdersDbContext. Endpoints take ISender, which dispatches commands and queries. Match turns the Result into a response: one function for success and one for the error.

  7. Run it.

    Terminal window
    dotnet run --urls http://localhost:5000

    In 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 400 with {"code":"VALIDATION",...}, and an unknown ID returns 404 with {"code":"NOT_FOUND",...}. The console shows a line from LoggingBehavior for every request.

  • Validation: replace the if in the handler with a FluentValidation validator that runs before it.
  • Caching: make GetOrderQuery cacheable 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.