Table of Contents

With minimal APIs

The command factory does not care what calls it. With minimal APIs, the endpoints ask for PostCommands as a parameter, and the rest is the same as in a controller: start the read, register the buffer, return the task of the rows.

public static IEndpointRouteBuilder MapPostEndpoints(
    this IEndpointRouteBuilder endpoints)
{
    RouteGroupBuilder posts = endpoints.MapGroup("minimal/posts");

    // Recommended: the pooled buffer, registered, then its
    // rows' task returned.
    posts.MapGet(
        "by-author/{author}",
        static (int author, PostCommands commands, HttpContext http)
            => commands
                .ByAuthor(author)
                .ToPooledBuffer(http.RequestAborted)
                .RegisterForDispose(http.Response));

    // A list: one expression, nothing to register.
    posts.MapGet(
        "by-author/{author}/list",
        static (int author, PostCommands commands, HttpContext http)
            => commands
                .ByAuthor(author)
                .ToListAsync(http.RequestAborted));

    return endpoints;
}

Program.cs reads the connection string from configuration (ConnectionStrings:Posts in appsettings.json), registers the command factory and maps the endpoints. MapPostEndpoints is the extension method above, in the static class PostEndpoints:

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
string connectionString = builder.Configuration
    .GetConnectionString("Posts")
    ?? throw new InvalidOperationException("No Posts connection string.");
builder.Services.AddPostCommands(connectionString);

WebApplication app = builder.Build();
app.MapPostEndpoints();

await app.RunAsync();

What each endpoint does:

  • The buffer. HttpContext is a parameter, for RequestAborted and the response. RegisterForDispose(http.Response) registers the buffer with the response and returns the task of its rows, which the lambda returns without awaiting it, as the controller does. The framework awaits the rows and writes them as a JSON array, and the arrays go back to the pool after the response. The rule is the controller's: never dispose a buffer whose rows you return (no using, no await using). See The controller and Caveats.
  • The list. ToListAsync returns a ValueTask<List<Post>>, and the endpoint returns it as it is, with nothing to register.

The tests on What to test work the same way: point the WebApplicationFactory client at the endpoint's route.