Vertical Slice Architecture in C#: .NET 10 Example & Errors
Last updated: October 30, 2026 · Tested with .NET 10.0.12 (SDK 10.0.401), ASP.NET Core minimal APIs, EF Core Sqlite 10.0.14, FluentValidation 12.2.0, MediatR 14.2.0, xUnit 2.9.3, Microsoft.AspNetCore.Mvc.Testing 10.0.14, Windows 11
Short answer: vertical slice architecture organises an ASP.NET Core app by feature instead of by layer: each use case (create a product, get a product) lives in one folder or one file with its request, validation, handler and endpoint, and slices don’t call each other. On .NET 10 you don’t need MediatR for it: a small IEndpoint interface plus minimal APIs is enough, and current MediatR versions are a commercial product that logs a license warning without a key. I built the same small shop both ways, tested each slice over HTTP, and broke it on purpose; the outputs below are from those runs.
| What went wrong | What you see | Section |
|---|---|---|
| Endpoint class injects the DbContext | Development: the app won’t start. Production: starts fine and keeps one DbContext forever | 4 |
| Two slices map the same route | AmbiguousMatchException: The request matched multiple endpoints at request time |
4 |
| Validator not registered | Unable to resolve service for type 'FluentValidation.IValidator`1[...]' |
4 |
Slice forgot : IEndpoint |
405 instead of 404 |
4 |
| MediatR without a license key | You do not have a valid license key for the Lucky Penny software MediatR |
5 |
Vertical Slice vs Clean Architecture in One Picture
In a layered or Clean Architecture project, one feature is spread over Controllers, Services, Repositories and DTO folders, and a change to “create product” touches four of them. In a vertical slice project the feature is the folder. This is the whole test app:
Shop/
├── Common/
│ ├── IEndpoint.cs
│ └── ValidationFilter.cs
├── Data/
│ └── ShopDb.cs
├── Features/
│ └── Products/
│ ├── CreateProduct.cs
│ ├── GetProduct.cs
│ └── ListProducts.cs
├── Program.cs
└── Shop.csproj
Common holds the few pieces every slice uses, Data holds the EF Core model, and everything else is a feature. The trade-off is deliberate: some duplication between slices in exchange for changes that stay inside one file. Vertical slices and Clean Architecture aren’t exclusive (you can slice the application layer of a Clean Architecture solution), but for most APIs the folder above is all the structure you need.
1. A Slice in One File
Each slice is a static class with its request, response, validator, endpoint and handler:
// One file = one use case: request, validation, handler and route.
public static class CreateProduct
{
public record Request(string Name, decimal Price, int Stock);
public record Response(int Id, string Name, decimal Price);
public sealed class Validator : AbstractValidator<Request>
{
public Validator()
{
RuleFor(r => r.Name).NotEmpty().MaximumLength(100);
RuleFor(r => r.Price).GreaterThan(0);
RuleFor(r => r.Stock).GreaterThanOrEqualTo(0);
}
}
public sealed class Endpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder app) =>
app.MapPost("/products", Handle)
.AddEndpointFilter<ValidationFilter<Request>>()
.WithTags("Products");
}
public static async Task<IResult> Handle(Request request, ShopDb db, CancellationToken ct)
{
var product = new Product { Name = request.Name, Price = request.Price, Stock = request.Stock };
db.Products.Add(product);
await db.SaveChangesAsync(ct);
return TypedResults.Created($"/products/{product.Id}", new Response(product.Id, product.Name, product.Price));
}
}
The handler is a static method, so minimal APIs inject ShopDb and the CancellationToken per request; no handler class, no mediator. A read slice doesn’t need a repository either; it projects straight from the DbContext into its own response type:
// A read slice can project straight from the DbContext: no repository, no shared service.
public static async Task<IResult> Handle(int id, ShopDb db, CancellationToken ct)
{
var product = await db.Products
.Where(p => p.Id == id)
.Select(p => new Response(p.Id, p.Name, p.Price, p.Stock > 0))
.SingleOrDefaultAsync(ct);
return product is null ? TypedResults.NotFound() : TypedResults.Ok(product);
}
GetProduct.Response has an InStock flag that CreateProduct.Response doesn’t. Each slice owns its shapes, so changing one never breaks another.
2. Registering Slices Without Touching Program.cs
The only shared contract is a one-method interface, plus two extension methods that find every implementation:
// Every slice exposes its route through one small interface.
public interface IEndpoint
{
void Map(IEndpointRouteBuilder app);
}
public static class EndpointExtensions
{
// Finds every IEndpoint in the assembly so Program.cs never changes when a slice is added.
public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
{
var endpoints = assembly.DefinedTypes
.Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IEndpoint)));
foreach (var type in endpoints)
services.AddTransient(typeof(IEndpoint), type);
return services;
}
public static WebApplication MapEndpoints(this WebApplication app)
{
foreach (var endpoint in app.Services.GetServices<IEndpoint>())
endpoint.Map(app);
return app;
}
}
builder.Services.AddDbContext<ShopDb>(o => o.UseSqlite(builder.Configuration.GetConnectionString("Shop") ?? "Data Source=shop.db"));
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
builder.Services.AddEndpoints(typeof(Program).Assembly);
var app = builder.Build();
app.MapEndpoints();
Validation is one generic endpoint filter, so slices only declare .AddEndpointFilter<ValidationFilter<Request>>():
// Runs the FluentValidation validator for TRequest before the handler and returns 400 with the errors.
public sealed class ValidationFilter<TRequest>(IValidator<TRequest> validator) : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var request = context.Arguments.OfType<TRequest>().Single();
var result = await validator.ValidateAsync(request, context.HttpContext.RequestAborted);
if (!result.IsValid)
return TypedResults.ValidationProblem(result.ToDictionary());
return await next(context);
}
}
3. Test Each Slice Through HTTP
Slices are tested the way they’re used: an HTTP request against the real pipeline with WebApplicationFactory, each test class with its own SQLite file:
private readonly WebApplicationFactory<Program> _factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(b => b.UseSetting("ConnectionStrings:Shop", $"Data Source=test-{Guid.NewGuid():N}.db"));
[Fact]
public async Task Create_with_invalid_data_returns_400_with_errors()
{
var client = _factory.CreateClient();
var response = await client.PostAsJsonAsync("/products", new { name = "", price = 0, stock = -1 });
output.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
Passed Shop.Tests.ProductSliceTests.List_filters_by_max_price [2 s]
[{"id":1,"name":"Mouse","price":19.5}]
Passed Shop.Tests.ProductSliceTests.Get_missing_product_returns_404 [65 ms]
Passed Shop.Tests.ProductSliceTests.Create_returns_201_with_location [52 ms]
201 /products/1 {"id":1,"name":"Keyboard","price":49}
Passed Shop.Tests.ProductSliceTests.Create_with_invalid_data_returns_400_with_errors [47 ms]
400 {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"Name":["'Name' must not be empty."],"Price":["'Price' must be greater than '0'."],"Stock":["'Stock' must be greater than or equal to '0'."]}}
Total tests: 4
Passed: 4
The validation test shows the filter end to end: three rules failed, and the response is a standard ValidationProblem with the errors per field. Testing over HTTP rather than calling handlers directly also covers routing, binding and the filter, which is where the bugs in section 4 live. Older guides tell you to add public partial class Program; so the test project can see Program; on .NET 10 I removed that line and all four tests still compiled and passed.
4. Four Mistakes and What They Look Like
I copied the app, made one change per run, and sent requests to it.
An endpoint class that injects the DbContext
Easy to write, because the endpoint class looks like a natural place for dependencies:
Features\Products\GetProduct.cs(11,41): warning CS9113: Parameter 'db' is unread.
log: Unhandled exception. System.InvalidOperationException: Cannot resolve 'System.Collections.Generic.IEnumerable`1[Shop.Common.IEndpoint]' from root provider because it requires scoped service 'Shop.Data.ShopDb'.
In Development the app doesn’t start. MapEndpoints resolves the endpoints once, at startup, from the root service provider, and a scoped DbContext can’t come from there. The same build in Production:
POST /products -> 201 {"id":1,"name":"Mouse","price":19.5}
GET /products/1 -> 200 {"id":1,"name":"Mouse","price":19.5,"inStock":true}
No error at all: Production doesn’t validate scopes by default, so the endpoint gets one ShopDb from the root provider that lives as long as the app. Any request that used it would share a single, never-disposed DbContext across threads. Endpoint classes only map routes; dependencies go in the handler’s parameters, which minimal APIs resolve per request.
Two slices with the same route
GET /products -> 500 Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches:
HTTP: GET /products => Handle
HTTP: GET /products
A new SearchProducts slice also mapped GET /products. Nothing failed at startup; the first request did. With slices spread over many files, this is the collision you get when two people add features at once. The integration tests in section 3 would catch it, which is one more reason to test over HTTP.
The validator isn’t registered
POST /products -> 500 System.InvalidOperationException: Unable to resolve service for type 'FluentValidation.IValidator`1[Shop.Features.Products.CreateProduct+Request]' while attempting to activate 'Shop.Common.ValidationFilter`1[Shop.Features.Products.CreateProduct+Request]'.
That’s what happens without AddValidatorsFromAssemblyContaining<Program>() (from the FluentValidation.DependencyInjectionExtensions package). Again: a runtime error on the first request, not at startup.
A slice that forgot “: IEndpoint”
GET /products -> 405
Not 404: the list slice was never mapped, but POST /products from the create slice still exists, so ASP.NET Core answers “method not allowed”. If a route you just added returns 405, check that its endpoint class implements the interface.
5. Do You Need MediatR?
Most vertical slice examples use MediatR: each slice has a request and an IRequestHandler, and the endpoint only calls Send. I added one MediatR slice to the same app with the current package (14.2.0):
public sealed class Handler(ShopDb db) : IRequestHandler<Query, int>
{
public Task<int> Handle(Query query, CancellationToken ct) => db.Products.CountAsync(ct);
}
GET /products/count -> 200 0
log: warn: LuckyPennySoftware.MediatR.License[0]
log: You do not have a valid license key for the Lucky Penny software MediatR. This is allowed for development and testing scenarios. If you are running in production you are required to have a licensed version. Please visit https://luckypennysoftware.com to obtain a valid license.
It works, and it logs that warning. MediatR is now a commercial product: per the message, free for development and testing, with a license key (cfg.LicenseKey or the MEDIATR_LICENSE_KEY environment variable, per the package’s own documentation) for production. Check the vendor’s terms for your situation; I’m only reporting what the package does.
For the slice itself MediatR adds little on top of minimal APIs: the endpoint filter already does what a validation pipeline behavior did, and a static handler method is a handler. Where it still earns its place is a large app that relies on its pipeline behaviors or notifications across many handlers. For a new API on .NET 10, start without it.
Vertical Slice Checklist
- One folder per feature area, one file (or folder) per use case.
- Each slice owns its request and response types; don’t share DTOs between slices.
- Read slices project straight from the DbContext; no generic repository.
- Endpoint classes only map routes; dependencies go in handler parameters.
- Validation as one generic endpoint filter, validators registered by assembly scan.
- An integration test per slice through
WebApplicationFactory; it catches duplicate routes and missing registrations. - Run locally in Development, where scope validation catches captured DbContexts.
- MediatR is optional; if you use it, budget for the license.
Reference: endpoint filters in minimal APIs on Microsoft Learn.
Related: Clean Architecture in C# · REST API with ASP.NET Core (.NET 10) · EF Core: the model has pending changes · all ASP.NET Core tutorials