Table of Contents

A controller with no service layer

The usual stack reads rows into entities, copies the entities into DTOs, collects the DTOs in a list and hands the list to the serializer. With Open.Database.Extensions the controller calls a query that a command factory defines once, takes the rows in a pooled buffer and returns them. ASP.NET Core writes the JSON from those rows, and the buffer's arrays go back to the pool after the response.

You define the command; the controller picks the shape of the result.

Two lanes. Classic: database, repository with a list of entities, service with a list of DTOs, serializer, JSON. Two sets of row objects and two lists, all left to the garbage collector. ODX: database, command factory with Post rows in pooled arrays, serializer, JSON. One set of row objects; after the response the arrays go back to the pool.

Side by side

Both versions read the posts of one author and write the same JSON. PostEntity and PostDto (not shown) have the same four properties as Post. The empty rows on the right are where the service was.

Classic: repository, service, DTOs

// Repository: rows into entities.
public sealed class PostRepository(string connectionString)
{
    public async Task<List<PostEntity>> ByAuthorAsync(
        int author,
        CancellationToken cancellationToken)
    {
        await using SqliteConnection connection
            = new(connectionString);
        IEnumerable<PostEntity> rows
            = await connection.QueryAsync<PostEntity>(
                new CommandDefinition(
                    ListSql,
                    new { author },
                    cancellationToken: cancellationToken));
        return rows.AsList();
    }
}

// Service: entities copied into DTOs.
public sealed class PostService(PostRepository repository)
{
    public async Task<List<PostDto>> ByAuthorAsync(
        int author,
        CancellationToken cancellationToken)
    {
        List<PostEntity> entities = await repository
            .ByAuthorAsync(author, cancellationToken);
        return entities
            .Select(static e => new PostDto
            {
                Id = e.Id,
                Author = e.Author,
                Title = e.Title,
                Body = e.Body,
            })
            .ToList();
    }
}

// Controller: the DTO list, for the serializer.
[ApiController]
[Route("classic/posts")]
public sealed class PostsController(PostService service)
    : ControllerBase
{
    [HttpGet("by-author/{author}")]
    public Task<List<PostDto>> ByAuthorAsync(int author)
        => service.ByAuthorAsync(
            author,
            HttpContext.RequestAborted);
}

ODX: a command factory, and nothing in between

// Command factory: each query defined once.
public sealed class PostCommands(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    ArrayPool<Post> pool)
{
    static readonly MappedDbQuery<Post> ByAuthorQuery
        = DbQuery.Text(ListSql).Map<Post>();

    // Bound, not run: the caller picks the terminal.
    public MappedQuery<Post> ByAuthor(int author)
        => ByAuthorQuery
            .Using(connectionFactory)
            .AddParam(author)
            .UsePool(pool, clearOnReturn: true);
}




// No service: nothing to copy.




















// Controller, recommended: the pooled rows, for the serializer.
[ApiController]
[Route("posts")]
public sealed class PostsController(PostCommands commands)
    : ControllerBase
{
    [HttpGet("by-author/{author}")]
    public Task<PooledArray<Post>> ByAuthorAsync(
        int author)
        => commands
            .ByAuthor(author)
            .ToPooledBuffer(HttpContext.RequestAborted)
            // The framework disposes it after the response,
            // and awaits the rows, then writes them.
            .RegisterForDispose(Response);
}

What is gone:

  • The repository becomes one definition, DbQuery.Text(...).Map<Post>(), made once in the command factory.
  • The service and its mapping code: there is nothing to copy.
  • The second set of objects. The rows exist once, as Post objects in pooled arrays. The classic version builds a list of entities, then a list of DTOs, and leaves both to the garbage collector.

The command factory

A command factory is a class that holds the queries of one area of the app. Each query is defined once: the SQL and the Map<Post>(), with no connection, immutable, safe in a static field.

Post is the model of Getting started, and ListSql is select * from posts where author = @author order by id.

The definition, ByAuthorQuery, is a MappedDbQuery<Post>. ByAuthor binds it to a connection factory, the author and a pool, and returns a MappedQuery<Post>: a query with everything it needs. Nothing runs yet: the call that reads the rows (the terminal) is the caller's choice. The same definition gives a pooled buffer to the controller above, a list to the one below, and a list to a test.

The entry point of the app provides the connection factory (SQLite in these samples) and the pool:

// Program.cs: the entry point provides the connection factory and the
// pool; the controllers ask for PostCommands.
public static IServiceCollection AddPostCommands(
    this IServiceCollection services,
    string connectionString)
    => services
        .AddSingleton<IDbConnectionFactory<SqliteConnection>>(
            new DbConnectionFactory<SqliteConnection>(
                ()
                    => new SqliteConnection(connectionString)))
        .AddSingleton(ArrayPool<Post>.Shared)
        .AddSingleton<PostCommands>();

Program.cs reads the connection string from configuration and calls it next to AddControllers(): builder.Services.AddPostCommands(connectionString);, then maps the controllers with app.MapControllers(). With minimal APIs shows those lines.

UsePool(pool, clearOnReturn) hands the query its pool; both arguments are required. clearOnReturn decides only for rows with no references: pass true when those values are sensitive, false to skip the clear. A Post holds strings, so its rows are always cleared before an array goes back, whatever you pass. See What is cleared.

The controller

Read the controller of the side-by-side from the top:

  1. ToPooledBuffer(HttpContext.RequestAborted) starts the read and returns the buffer at once; the read stops when the client leaves.
  2. RegisterForDispose(Response) hands the buffer to the framework, which disposes it when the request is over, and returns the task of the rows. Caveats says what was observed when a request fails.
  3. The action returns that task as it is: nothing in the action runs after the rows are ready, so there is no async and no await. The framework awaits it. The task completes when the read is over and the connection released, so nothing waits on the database while the JSON is written.
  4. The declared type is Task<PooledArray<Post>>. A PooledArray<Post> is an IReadOnlyList<Post>, so the JSON is the same: System.Text.Json writes it as an array.
  5. After the response is written, the framework disposes the buffer, and the arrays go back to the pool.
A timeline of one request. The action starts the read, registers the buffer and returns at once. The connection is open only while the read runs. The rows stay in pooled arrays from the read until the response is over. The framework awaits the rows, then writes the JSON. When the response is over the framework disposes the buffer and the arrays go back to the pool.

What was observed on Kestrel and on TestServer, with a client abort and an action that throws, is on Returning it from a controller. The use case behind the buffer is on The controller story.

RegisterForDispose

Copy this extension into your app. The framework disposes the buffer after the response, so the arrays go back to the pool:

// In your app: the framework disposes the buffer after the
// response, so the arrays go back to the pool.
public static class PooledBufferHttpExtensions
{
    public static Task<PooledArray<T>> RegisterForDispose<T>(
        this PooledBuffer<T> buffer,
        HttpResponse response)
    {
        ArgumentNullException.ThrowIfNull(buffer);
        ArgumentNullException.ThrowIfNull(response);

        response.RegisterForDispose(buffer);
        return buffer.Items;
    }
}

The action then reads as above: commands.ByAuthor(author).ToPooledBuffer(HttpContext.RequestAborted).RegisterForDispose(Response).

Or a list

The buffer is the default, whatever the size of the result: the rows exist once, as Post objects in pooled arrays, no list is built, and the arrays are reused by the next request. It is not faster: on a synthetic provider, dumping a result into a buffer held the reader 3.4% longer than ToArrayAsync at zero latency (the whole call 11.0% longer), and about as long on a simulated link. See What it costs.

Take a List<Post> when you need a list that you keep or change. The same command factory gives one (here the action only returns it, to show the shape):

// The plain alternative: a List<Post> that the garbage collector
// takes after the response. Nothing to register.
[HttpGet("by-author/{author}")]
public ValueTask<List<Post>> ByAuthorAsync(int author)
    => commands
        .ByAuthor(author)
        .ToListAsync(HttpContext.RequestAborted);

ToListAsync returns a ValueTask<List<Post>>, and the action returns it as it is, like the buffer's task. There is nothing to register, and the list is yours. What it costs: the rows are read into pooled chunks and then copied once into the list, and the list is garbage after the response. See When to use something else.

ETag: read the rows twice

The rows of a buffer (buffer.Items) stay in memory as an IReadOnlyList<Post>, so they can be read twice: once to compute an ETag, then again by the serializer. When the client already has those rows, the answer is 304 Not Modified and nothing is serialized.

[HttpGet("by-author/{author}")]
public async Task<ActionResult<IReadOnlyList<Post>>> ByAuthorAsync(
    int author)
{
    PooledArray<Post> posts = await commands
        .ByAuthor(author)
        .ToPooledBuffer(HttpContext.RequestAborted)
        .RegisterForDispose(Response);

    // First pass: a weak ETag of the values. A 304 carries it too.
    EntityTagHeaderValue etag = new(ETagOf(posts), isWeak: true);
    Response.GetTypedHeaders().ETag = etag;

    IList<EntityTagHeaderValue> ifNoneMatch
        = Request.GetTypedHeaders().IfNoneMatch;
    if (ifNoneMatch.Any(tag
        => tag.Equals(EntityTagHeaderValue.Any)
        || tag.Compare(etag, useStrongComparison: false)))
    {
        return StatusCode(StatusCodes.Status304NotModified);
    }

    // Second pass: the serializer walks the same rows.
    return Ok(posts);
}

The hash covers every field the response carries, in order, and it encodes the text as UTF-8, so it is the same on every server:

// A hash of every field the response carries.
static string ETagOf(PooledArray<Post> posts)
{
    using IncrementalHash hash
        = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);

    foreach (Post post in posts)
    {
        Append(hash, post.Id);
        Append(hash, post.Author);
        Append(hash, post.Title);
        Append(hash, post.Body);
    }

    return $"\"{Convert.ToHexString(hash.GetCurrentHash())}\"";
}

static void Append(IncrementalHash hash, int value)
{
    Span<byte> bytes = stackalloc byte[sizeof(int)];
    BinaryPrimitives.WriteInt32LittleEndian(bytes, value);
    hash.AppendData(bytes);
}

// The byte count first, so that "ab" + "c" and "a" + "bc" differ.
// UTF-8, so the bytes are the same on every machine.
static void Append(IncrementalHash hash, string? value)
{
    if (value is null)
    {
        Append(hash, -1);
        return;
    }

    byte[] utf8 = ArrayPool<byte>.Shared
        .Rent(Encoding.UTF8.GetMaxByteCount(value.Length));
    int written = Encoding.UTF8.GetBytes(value, utf8);
    Append(hash, written);
    hash.AppendData(utf8, 0, written);
    ArrayPool<byte>.Shared.Return(utf8);
}
  • When Post gains a field that the response carries, add it to the hash, or clients keep a 304 for rows that changed.
  • A stream from ToPooledStream can be read once: a second enumeration throws InvalidOperationException. To hash it and then write it, you would query again or copy the rows first.
  • The query still runs. A 304 saves the serialization and the bytes on the wire, not the read.
  • The 304 carries the ETag, as a 200 would.
  • If you change the JSON options (property names, say), clients keep ETags that still match: put a version string into the hash when you do.

What to test

With no service layer there is no pass-through code to mock. What is left to test is the SQL with its mapping, and the endpoint. The tests below are written for xUnit v3, and the samples project compiles and runs them against its in-memory SQLite database.

The command factory, on a real database. The SQL and the mapping are the logic, so test them where they run. DatabaseFixture is yours to write: its constructor creates and fills the test database, and its ConnectionFactory property is an IDbConnectionFactory<SqliteConnection> for that database. Every test class that touches that database joins one xUnit collection, so the database is filled once and one class does not read while another writes.

// Every class that touches the test database joins this collection: the
// database is filled once, and the classes do not run at the same time.
[CollectionDefinition(nameof(DatabaseCollection))]
public sealed class DatabaseCollection : ICollectionFixture<DatabaseFixture>;

// The command factory, against a real database: the SQL and the mapping.
[Collection(nameof(DatabaseCollection))]
public sealed class PostCommandsTests(DatabaseFixture database)
{
    [Fact]
    public async Task ByAuthorReadsThatAuthorsPosts()
    {
        PostCommands commands = new(
            database.ConnectionFactory,
            ArrayPool<Post>.Shared);

        List<Post> posts = await commands
            .ByAuthor(42)
            .ToListAsync(TestContext.Current.CancellationToken);

        Assert.Equal([1, 2, 3], posts.Select(static p => p.Id));
        Assert.All(posts, static p => Assert.Equal(42, p.Author));
    }
}

The controller, end to end, with WebApplicationFactory from Microsoft.AspNetCore.Mvc.Testing, and one lifetime guard: every array the request rented came back to the pool.

// The controller, end to end: routing, the query, the JSON.
[Collection(nameof(DatabaseCollection))]
public sealed class PostsEndpointTests(WebApplicationFactory<Program> app)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task ReturnsThePostsAsJson()
    {
        using HttpClient client = app.CreateClient();

        List<Post>? posts = await client.GetFromJsonAsync<List<Post>>(
            "posts/by-author/42",
            TestContext.Current.CancellationToken);

        Assert.NotNull(posts);
        Assert.Equal([1, 2, 3], posts.Select(static p => p.Id));
    }

    // The lifetime guard: every array the request rented came back.
    [Fact]
    public async Task GivesEveryArrayBack()
    {
        CountingPool<Post> pool = new();
        await using WebApplicationFactory<Program> counted = app
            .WithWebHostBuilder(web => web.ConfigureServices(
                services => services.AddSingleton<ArrayPool<Post>>(pool)));
        using HttpClient client = counted.CreateClient();

        using HttpResponseMessage response = await client.GetAsync(
            "posts/by-author/42",
            TestContext.Current.CancellationToken);
        response.EnsureSuccessStatusCode();

        // The framework disposes the buffer once the response is sent,
        // so the client can get here first: give it up to five seconds.
        using CancellationTokenSource limit = new(TimeSpan.FromSeconds(5));
        while (pool.Returned < pool.Rented && !limit.IsCancellationRequested)
            await Task.Delay(10, TestContext.Current.CancellationToken);

        Assert.True(pool.Rented > 0);
        Assert.Equal(pool.Rented, pool.Returned);
    }
}
  • CountingPool<T> is the pool on Your own pool. The test hands it in through the services.
  • The client can see the response before the framework disposes the buffer, so the guard waits for the arrays, with a time limit.
  • The guard is the test that fails when the action on the route it requests does not call RegisterForDispose: the response is the same and no array comes back.
  • Run the guard on a request that succeeds. When the action threw, or the client aborted during the read, the test server did not dispose what the request had registered; Kestrel did (the samples project checks both, for this form too). See the note on Returning it from a controller.

Caveats

  • Nothing may hold the rows past the response. Do not keep the PooledArray<Post> in a field or a cache, and do not hand it to work that outlives the request: once the buffer is disposed, the view throws ObjectDisposedException. Copy what you keep with ToList(). See Lifetime and ownership.
  • Register before you return the task. RegisterForDispose does; written by hand, call Response.RegisterForDispose(buffer) before return buffer.Items, so that the framework disposes it when the request is over. On Kestrel, with this form, a registered buffer was disposed when the client aborted during the read and when the action threw after it registered the buffer (before it returned the task, or in an async variant after the rows were read): every array went back to the pool. On an abort the action's task faults with OperationCanceledException; a throw answers 500.
  • Do not dispose it in the action. A using or an await using on a buffer whose rows the action returns disposes it before the framework serializes them; with await using, the response on Kestrel was a 500. See The trap.
  • The buffer holds the whole result until the response is written. For a very large result, return the stream: see A very large result.