In an ASP.NET Core vertical-slice layout, what does one feature folder contain, and what makes a Minimal API endpoint over its handler thin?
answer
- organise by feature, not by layer
- request, handler, response together
- endpoint binds, calls, translates
- handler resolved from DI
- TypedResults and Results<T1, T2>
basics
~20 sA feature folder holds everything for one use case: the request and response types, the handler with its data access, validation and the endpoint mapping. A thin endpoint only binds input, calls the handler and turns its outcome into TypedResults.
solid answer
~50 sVertical slices group code by use case instead of by layer, so `Features/Appointments/BookAppointment/` holds the `BookAppointment` request record, the response record, the handler that does the work, its validator and the endpoint that maps it. Changing a feature touches one folder instead of four projects. Inside a slice the handler can use the `DbContext` directly, and query handlers and command handlers can look different: a query projects with `AsNoTracking` and `Select`, a command loads the entity, changes it and calls `SaveChangesAsync`. The endpoint stays **thin**: it binds the request, takes the handler from DI as a parameter, calls it with the request's `CancellationToken`, and translates the outcome into `TypedResults` such as `Created` or `NotFound`. No EF Core query and no business rule lives in the lambda. A mediator such as MediatR's `ISender` is optional; a plain handler class registered with `AddScoped` works.
code
csharp · 18 lines// Features/Appointments/BookAppointment/BookAppointmentHandler.cs
public sealed record BookAppointment(int PatientId, int VetId, DateTimeOffset StartsAt);
public sealed record BookAppointmentResponse(int AppointmentId);
public sealed class BookAppointmentHandler(VetDbContext db)
{
public async Task<BookAppointmentResponse?> Handle(BookAppointment cmd, CancellationToken ct)
{
var clash = await db.Appointments.AnyAsync(
a => a.VetId == cmd.VetId && a.StartsAt == cmd.StartsAt, ct);
if (clash) return null;
var appointment = new Appointment(cmd.PatientId, cmd.VetId, cmd.StartsAt);
db.Appointments.Add(appointment);
await db.SaveChangesAsync(ct);
return new BookAppointmentResponse(appointment.Id);
}
}go deeper
Describe a feature folder and the three jobs of a thin endpoint: bind the input, call the handler, return a TypedResults value.
Explain how the handler reaches the endpoint through DI, why a command and a query handler use EF Core differently, and how Results<T1, T2> documents the outcomes.
Discuss where shared rules live, how much duplication between slices you accept, and when a mediator's pipeline earns its dependency and licence.
Judge when slices beat layer projects for a team, and how you keep a slice-based codebase from drifting into fat endpoints without the compiler's help.
## Slicing by feature instead of by layer A **vertical slice** is one use case cut through every technical layer: HTTP shape, validation, business logic and data access together. Instead of a `Controllers` folder, a `Services` folder and a `Repositories` folder, the project has `Features/`, and each use case owns a folder. For a veterinary practice: - `Features/Appointments/BookAppointment/` holds `BookAppointment` (the request record), `BookAppointmentResponse`, `BookAppointmentHandler`, a validator and the endpoint mapping. - `Features/Appointments/GetDaySchedule/` holds the query, its response, its handler and its endpoint. - `Features/Patients/RegisterPatient/` follows the same shape. Shared things that are genuinely shared, such as `VetDbContext` or the `Appointment` entity, live outside the feature folders. A slice can be one file with nested types or several small files; the rule is that the code for one feature changes together and lives together. ## What the handler does The handler is an ordinary class with one public method. Because each slice is independent, slices may implement their data access differently, which is the CQRS-style split many teams adopt: | Slice kind | Typical EF Core use | Returns | |---|---|---| | Query (`GetDaySchedule`) | `AsNoTracking()`, `Where`, `Select` into a response record, `ToListAsync` | a read model shaped for the screen | | Command (`BookAppointment`) | load the entity or create it, apply domain rules, `Add`, `SaveChangesAsync` | an id or an outcome | | Bulk command (`CancelDay`) | `ExecuteUpdateAsync` on a filtered query | the number of rows changed | Because `AddDbContext` registers `VetDbContext` as **scoped**, every handler resolved during one request shares the same context, so a command's single `SaveChangesAsync` call commits all its changes as one unit. ## What makes the endpoint thin A thin endpoint has three jobs and nothing else: 1. **Bind** the input: route values, query string and the JSON body into the request record. 2. **Call** the handler, passing the request's `CancellationToken`. 3. **Translate** the handler's outcome into an HTTP result with `TypedResults`, declaring the possible results in the signature with `Results<Created<BookAppointmentResponse>, Conflict>` so the OpenAPI document lists both. The handler arrives as a lambda parameter. Minimal APIs resolve a parameter from DI when its type is registered as a service, so `builder.Services.AddScoped<BookAppointmentHandler>()` is required; otherwise the complex type is treated as the request body. What must **not** appear in the lambda: an EF Core query, a `SaveChangesAsync` call, a business rule such as "a vet cannot be double-booked", or mapping logic more than a line long. If the lambda grows those, the slice has lost its handler and the endpoint has become the handler. ## One request through a slice Following `POST /appointments` from start to finish shows where each responsibility sits: 1. Routing matches the `MapPost` endpoint and the JSON body is deserialised into the `BookAppointment` record. 2. A request scope already exists, so the scoped `BookAppointmentHandler` and the scoped `VetDbContext` it depends on are resolved from it. 3. The endpoint awaits `handler.Handle(cmd, ct)`. 4. The handler checks the double-booking rule with one `AnyAsync` query, adds the `Appointment` and calls `SaveChangesAsync` once. 5. The endpoint turns a `null` outcome into `TypedResults.Conflict()` (409) and a success into `TypedResults.Created(...)` (201 with a `Location` header). Only step 5 knows about status codes, and only step 4 knows about the database. That separation, not the folder name, is what makes the slice maintainable. ## Controllers and mediators The same shape works in an MVC controller: the action method receives the request, calls the handler and returns an `ActionResult`. Many teams route the call through a mediator, `await sender.Send(command, ct)` with MediatR's `ISender`, which adds pipeline behaviours for cross-cutting work. That is a choice, not a requirement of vertical slices; MediatR 14 is a Lucky Penny product under the RPL-1.5 or a paid licence, and a directly injected handler class is the simplest thin endpoint. ## Trade-offs to state in an interview - Slices make a feature easy to find, change and delete, and keep merge conflicts local to one folder. - They tolerate some duplication between slices in exchange for independence; extract shared code only when a real rule is shared. - Without the compiler enforcing layers, discipline comes from code review and from keeping the endpoint thin. - Slices and clean-architecture projects are not exclusive: many solutions keep a `Domain` project for the rules and organise `Application` by feature.
- Two slices need the same rule, say that a vet's appointments cannot overlap. Where does it go?Into the shared domain model, typically a method on the `Appointment` entity or a small domain service both handlers call, not into one slice that the other then imports. Slices may duplicate plumbing, but a business rule that must stay identical belongs in one place both depend on.
- Why pass the CancellationToken from the endpoint into the handler?Minimal APIs bind a `CancellationToken` parameter to `HttpContext.RequestAborted`. Passing it to `ToListAsync`, `AnyAsync` and `SaveChangesAsync` lets EF Core abandon the database work when the client disconnects, instead of finishing a query nobody will read.
- Vertical slices forbid handlers from using the DbContext directly.
- Vertical slices require MediatR; without a mediator there are no slices.
- A thin endpoint can run the EF Core query itself as long as it is short.
- Each slice must have its own DbContext to stay independent.
- A feature folder is one folder per entity holding all of its endpoints and services.