Project templates
Vitreous.Templates is a dotnet new template pack. A template gives you a project that builds, runs and passes its tests on the first try, with the handlers, behaviors and HTTP mapping already wired up the way the rest of these docs describe.
dotnet new install Vitreous.Templatesdotnet new vitreous-api -n Shopcd Shopdotnet run --project src/Shop| Template | Creates |
|---|---|
vitreous-api |
An ASP.NET Core minimal API |
vitreous-console |
A command-line app on the .NET Generic Host |
vitreous-worker |
A background service that polls on a timer |
vitreous-clean |
A layered solution: Domain, Application, Infrastructure and one of the hosts above |
vitreous-command, -query, -notification, -behavior |
A message and its handler, or a pipeline behavior, in an existing project |
The API, the console app and the worker are organized in vertical slices: each feature keeps its command or query, validator, handler and entry point (an endpoint, or a verb on the command line) in one file, so you read, change or delete a feature in one place. vitreous-clean is organized in layers, so the business rules can’t depend on the database or the app around them. Start with slices unless you have business rules worth protecting: one project is less to navigate, and Vitreous works the same in both.
Each generated project has a README.md that explains its layout, how to run and test it, and where the next feature goes.
vitreous-api
Section titled “vitreous-api”An ASP.NET Core minimal API.
Shop/ Shop.slnx Shop.sln with -f net8.0 Directory.Build.props target framework, nullable, warnings as errors Directory.Packages.props every package version, in one place src/Shop/ Program.cs registration: handlers, behaviors, validation, caching, DevUI Common/ ResultHttpExtensions.cs ToHttpResult(): Error.Code → status code LoggingBehavior.cs an open-generic pipeline behavior Features/Todos/ CreateTodo.cs command + validator + handler + endpoint GetTodo.cs query ListTodos.cs stream query CompleteTodo.cs command without a result, publishes TodoCompleted TodoCompleted.cs notification and its handler TodoStore.cs in-memory storage tests/Shop.Tests/ endpoint tests (WebApplicationFactory) and handler testsThe todos are kept in memory, so the project runs with no setup. Handlers return failures as an Error, and ToHttpResult() turns them into Problem Details responses. A validation failure becomes a 400 with the messages per property, as described in Validation and HTTP error mapping. In Development, the app serves the OpenAPI document at /openapi/v1.json, the Scalar API reference at /scalar/v1 and the developer UI at /vitreous.
vitreous-console
Section titled “vitreous-console”A command-line app on the .NET Generic Host, with the same todos.
dotnet new vitreous-console -n Shop.Clicd Shop.Clidotnet run --project src/Shop.Cli -- add Buy milkdotnet run --project src/Shop.Cli -- listsrc/Shop.Cli/ Program.cs registration, the scope and Ctrl+C appsettings.json Common/ ExitCodes.cs ToExitCode(): Error.Code → exit code, errors to stderr CliOutput.cs stdout and stderr, replaced in the tests LoggingBehavior.cs an open-generic pipeline behavior Features/Todos/ TodoCli.cs maps the arguments to the verbs CreateTodo.cs command + validator + handler + verb GetTodo.cs, ListTodos.cs, CompleteTodo.cs, TodoCompleted.cs TodoStore.cs keeps the todos in a JSON filetests/Shop.Cli.Tests/ whole command lines, and handler testsHandlers are scoped, and so is ISender. A console app has no requests to give it a scope, so Program.cs creates one and sends from it. Results go to stdout, errors and logs to stderr, and the exit code is 0 on success, 1 when a handler returns an error, 2 for wrong arguments or invalid input, and 130 after Ctrl+C. The arguments are matched with a list pattern, so there is no parsing library to learn or replace.
vitreous-worker
Section titled “vitreous-worker”A worker service that sends reminders when they are due.
dotnet new vitreous-worker -n Shop.Jobscd Shop.Jobsdotnet run --project src/Shop.Jobssrc/Shop.Jobs/ Program.cs registration, and sample reminders for the first run appsettings.json Reminders:Interval Common/ LoggingBehavior.cs an open-generic pipeline behavior Features/Reminders/ ReminderWorker.cs BackgroundService: the timer, and a scope per unit of work GetDueReminders.cs query GetRecipient.cs query SendReminder.cs command + validator + handler, publishes ReminderSent ReminderSent.cs notification and its handler ReminderStore.cs in-memory storagetests/Shop.Jobs.Tests/ worker tests with a fake clock, and handler testsA hosted service is a singleton, so it can’t take the scoped ISender in its constructor. ReminderWorker takes an IServiceScopeFactory and opens a scope for each query and command it sends:
await using var scope = scopes.CreateAsyncScope();await work(scope.ServiceProvider.GetRequiredService<ISender>());A failed Result is logged and tried again on the next tick, and an unexpected exception is logged instead of stopping the host. On Ctrl+C or SIGTERM, the handler that is running gets a cancelled token and nothing new starts. The timer and the handlers read the time from TimeProvider, so the tests move the clock forward instead of waiting.
vitreous-clean
Section titled “vitreous-clean”The layers of Clean Architecture around a DDD aggregate, with an API, a console app or a worker on top.
dotnet new vitreous-clean -n Shopdotnet new vitreous-clean -n Shop.Jobs --host workerShop/ src/ Shop.Domain/ references Vitreous, for its abstractions only Money.cs value object IHasDomainEvents.cs Orders/ Order aggregate, OrderLine, OrderId, OrderPlaced, OrderShipped Shop.Application/ DependencyInjection.cs AddApplication(): behaviors and validators Abstractions/ IAppDbContext, IEmailSender Common/LoggingBehavior.cs Orders/ PlaceOrder.cs command + validator + handler ShipOrder.cs command without a result GetOrder.cs query ListOrders.cs stream query EmailCustomer.cs handles the domain events Shop.Infrastructure/ DependencyInjection.cs AddInfrastructure(): EF Core, email, caching Persistence/ AppDbContext, and how Order is mapped Email/ Shop.Api/ or Shop.Cli, or Shop.Worker tests/ Shop.Domain.Tests/ business rules, as plain classes Shop.Application.Tests/ handlers on a SQLite in-memory database Shop.Architecture.Tests/ the dependency rule Shop.Api.Tests/ the whole app, over HTTP- The domain decides.
Orderchanges only through its methods, and each returns aResult, so an order that breaks a business rule can’t exist. It records domain events, which are plain notifications. - No repositories. Handlers use EF Core through
IAppDbContext, which Application declares and Infrastructure’sAppDbContextimplements.SaveChangesAsyncsaves, then publishes the domain events of the saved entities. - The dependency rule is a test.
Shop.Architecture.Testslists the assemblies each layer may use, and fails when one uses another. - The generator is on the host only. It finds the handlers of every layer at build time.
--host changes the host project and its tests, and nothing else:
--host |
Project | What it does |
|---|---|---|
api (default) |
Shop.Api |
Minimal API endpoints, OpenAPI + Scalar, and the developer UI in Development |
console |
Shop.Cli |
place, list, show and ship verbs, with the exit codes of vitreous-console. Named Cli because code in a Shop.Console namespace couldn’t call Console.WriteLine. |
worker |
Shop.Worker |
Ships the placed orders on a timer, with a scope per unit of work as in vitreous-worker |
The orders are in a SQLite file that the app creates on its first run with EnsureCreated. Switch to EF Core migrations before you have data to keep. The reasoning behind the layers is in Clean Architecture and DDD.
Options
Section titled “Options”| Option | Templates | Values | Default | What it does |
|---|---|---|---|---|
-f, --framework |
all | net8.0 net9.0 net10.0 net11.0 |
net10.0 |
The target framework. Package versions follow it, e.g. Microsoft.Extensions.Hosting 9.x on net9.0. On net8.0, the solution is a .sln because the .NET 8 SDK can’t read .slnx, and in the API templates Swashbuckle generates the OpenAPI document, because AddOpenApi() arrived in .NET 9. |
--host |
vitreous-clean |
api console worker |
api |
The app on top of the layers. |
--validation |
all | true false |
true |
Adds Vitreous.FluentValidation and a validator. |
--caching |
all but vitreous-console |
none memory redis |
none |
Caches a query (GetTodoQuery, GetRecipientQuery or GetOrderQuery becomes an ICacheableQuery). memory uses the in-memory IDistributedCache. redis uses Vitreous.Caching.Redis, reads the Redis connection string, and adds a compose.yaml that runs Redis locally. See Caching. |
--devui |
vitreous-api, vitreous-clean --host api |
true false |
true |
Adds Vitreous.DevUI, which is on in Development only. |
--aot |
vitreous-api |
true false |
false |
Publishes with Native AOT: CreateSlimBuilder, PublishAot and a source-generated JsonSerializerContext for every type an endpoint reads or writes. See Native AOT. |
--tests |
all | true false |
true |
Adds the xUnit test project, or projects. |
--vitreous-version |
all | a version | the template pack’s own | The version of the Vitreous packages to reference. |
--no-restore |
all | Skips the restore after the project is created. |
dotnet new vitreous-api -n Shop -f net8.0dotnet new vitreous-api -n Shop --caching redisdotnet new vitreous-api -n Shop --aot --caching memorydotnet new vitreous-worker -n Shop.Jobs --caching redisdotnet new vitreous-clean -n Shop --host console -f net9.0Item templates
Section titled “Item templates”Item templates add a file to a project that already uses Vitreous, whether a template created it or not. Run them in the folder the file belongs in:
cd src/Shop/Features/Ordersdotnet new vitreous-command -n PlaceOrder --result Guid --validationusing FluentValidation;using Vitreous;using Vitreous.Abstractions;
namespace Shop.Features.Orders;
public sealed record PlaceOrderCommand : ICommand<Guid>;
public sealed class PlaceOrderValidator : AbstractValidator<PlaceOrderCommand>{ public PlaceOrderValidator() { // RuleFor(c => c.Name).NotEmpty(); }}
public sealed class PlaceOrderHandler : ICommandHandler<PlaceOrderCommand, Guid>{ public ValueTask<Result<Guid>> Handle(PlaceOrderCommand command, CancellationToken ct = default) { // Return the value, or an Error such as Error.NotFound("...") when it fails. throw new NotImplementedException(); }}| Template | -n |
File | Creates |
|---|---|---|---|
vitreous-command |
PlaceOrder |
PlaceOrder.cs |
PlaceOrderCommand and PlaceOrderHandler |
vitreous-query |
GetOrder |
GetOrder.cs |
GetOrderQuery and GetOrderHandler |
vitreous-notification |
OrderPlaced |
OrderPlaced.cs |
OrderPlaced and OrderPlacedHandler |
vitreous-behavior |
Retry |
RetryBehavior.cs |
RetryBehavior<TMessage, TResult>, for every command and query |
-n PlaceOrderCommand gives the same result as -n PlaceOrder. The source generator registers the handler at build time. A pipeline behavior has to be added, because the order matters: services.AddVitreousBehavior(typeof(RetryBehavior<,>)).
| Option | Templates | Default | What it does |
|---|---|---|---|
--result <type> |
command, query | The type the message returns. Without it, a command returns no value (ICommand), and a query gets an empty GetOrderResponse record to fill in. Quote a generic type: --result "List<OrderDto>". |
|
--validation |
command, query | false |
Adds a validator. The project needs Vitreous.FluentValidation, see Validation. |
--handler |
notification | true |
--handler false creates the notification alone, for a domain event whose handlers are in another layer. |
--namespace <name> |
all | from the folder | The namespace. The default is the project’s root namespace plus the folder you run the command in. |
The item templates only run inside a restored C# project. dotnet new install says so when you run it anywhere else, as “might not work because their constraints are not met”, and dotnet new list hides them there.
Versions
Section titled “Versions”A template references the Vitreous version it shipped with: Vitreous.Templates 0.6.0 creates projects on Vitreous 0.6.0. Update the template pack with dotnet new update, or pass --vitreous-version to create a project on another release. Vitreous and Vitreous.SourceGeneration should stay on the same version: when you upgrade, change both in Directory.Packages.props.