Lesson 87 of 93 · 5 min read · Updated

Async Fixture Lifecycle in xUnit: IAsyncLifetime and ICollectionFixture for Containers

Starting a container is asynchronous, and so is stopping it. A constructor cannot await, and IDisposable.Dispose cannot either, so a container fixture needs a different hook. xUnit provides IAsyncLifetime for this, and ICollectionFixture lets many test classes share one expensive fixture. This lesson shows how the two work together and what you trade when you share a container.

Technical Requirements

  1. .NET 11 SDK
  2. Docker
  3. xUnit 2.9.3
  4. Testcontainers.PostgreSql and Testcontainers.Redis 4.17.0
  5. Respawn 7.0.0 (used for the reset step)

IAsyncLifetime: Async Setup and Guaranteed Teardown

In xUnit 2.x, IAsyncLifetime has two methods: Task InitializeAsync() and Task DisposeAsync(). xUnit calls InitializeAsync after it creates the fixture and before any test uses it, and calls DisposeAsync when the fixture is no longer needed. In xUnit v3 the same interface returns ValueTask, but the idea is identical.

The fixture does all its async work in InitializeAsync: start the containers, connect to Redis, apply migrations and prepare the database reset.

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

public sealed class InfrastructureFixture : IAsyncLifetime
{
public async Task InitializeAsync()
{
// We start the two containers IN PARALLEL: this saves the suite seconds.
// StartAsync waits UNTIL the container is READY (wait strategy);
// an observable condition instead of "waiting and hoping" with Thread.Sleep.
await Task.WhenAll(_postgres.StartAsync(), _redis.StartAsync());

// allowAdmin: needed for admin commands such as FLUSHDB.
// Deterministic RESET between tests depends on it; do NOT enable it in production.
var redisOptions = ConfigurationOptions.Parse(_redis.GetConnectionString());
redisOptions.AllowAdmin = true;

Redis = await ConnectionMultiplexer.ConnectAsync(redisOptions);

// APPLY THE MIGRATIONS (Migrate, not EnsureCreated).
await using var db = CreateDbContext();
await db.Database.MigrateAsync();

// The Respawner is created AFTER the migrations, ONCE per fixture.
_respawnConnection = new NpgsqlConnection(PostgresConnectionString);
await _respawnConnection.OpenAsync();

_respawner = await Respawner.CreateAsync(_respawnConnection, new RespawnerOptions
{
DbAdapter = DbAdapter.Postgres,
SchemasToInclude = ["public"],
TablesToIgnore = ["__EFMigrationsHistory"],
});

await SeedReferenceDataAsync();
}

public async Task DisposeAsync()
{
// Cleanup MUST be guaranteed: a leaked container fills up the CI agent.
await _respawnConnection.DisposeAsync();
await Redis.DisposeAsync();
await _redis.DisposeAsync();
await _postgres.DisposeAsync();
}
}

The excerpt leaves out the field declarations for the two containers. The order in DisposeAsync is the reverse of the order in InitializeAsync. Client connections close first, then the containers stop. Closing a container while a connection is still open can produce noisy errors in the test output.

Why does disposal matter so much? On a laptop, a forgotten container wastes memory until you notice it. On a self-hosted CI agent that runs many builds a day, leaked containers pile up until the agent runs out of memory or ports. DisposeAsync together with WithCleanUp(true) on the builders makes sure the containers go away even when tests fail.

ICollectionFixture: One Container for Many Test Classes

A class fixture (IClassFixture<T>) is created once per test class. With three database test classes, that means three PostgreSQL containers. A collection fixture is created once per collection, and every class in the collection receives the same instance.

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

/// <summary>
/// Containers are EXPENSIVE. With a collection fixture all test classes share
/// ONE PostgreSQL and ONE Redis instance.
///
/// The price: classes in this collection do not run in parallel with each other.
/// The payoff: the suite does not take minutes instead of seconds.
/// </summary>
[CollectionDefinition(Name)]
public sealed class InfrastructureCollection : ICollectionFixture<InfrastructureFixture>
{
public const string Name = "Gerçek Altyapı";
}

A test class joins the collection with the [Collection] attribute and receives the fixture through its constructor. Here it uses a primary constructor:

M10.ContainerApi.Tests/PostgresBehaviourTests.cs

[Collection(InfrastructureCollection.Name)]
public class PostgresBehaviourTests(InfrastructureFixture fixture) : IAsyncLifetime
{
private static readonly DateTimeOffset Now = new(2026, 3, 14, 10, 0, 0, TimeSpan.Zero);

public Task InitializeAsync() => fixture.ResetDatabaseAsync();

public Task DisposeAsync() => Task.CompletedTask;

Note that the test class also implements IAsyncLifetime. xUnit creates a new instance of the test class for every test, so this InitializeAsync runs before each test. That is where the shared database is reset. The fixture's InitializeAsync runs once for the whole collection; the test class's InitializeAsync runs once per test.

HookRunsUsed for
InfrastructureFixture.InitializeAsyncOnce per collectionStart containers, migrate, build the Respawner
Test class InitializeAsyncBefore every testReset database rows (and the cache)
Test class DisposeAsyncAfter every testNothing here
InfrastructureFixture.DisposeAsyncOnce, after the last testClose connections, remove containers

Choosing the Lifecycle Scope

There are three common ways to scope a container. They trade isolation against cost:

ScopeIsolationCost
A new container per testStrongestVery slow
Collection fixture plus reset (this example)Depends on the resetReasonable
One container per suite, no resetTests pollute each otherFastest

A new container per test gives perfect isolation, but a PostgreSQL start costs a few seconds, and fifty tests would cost minutes. A shared container without a reset is fast, but a row written by one test leaks into the next, and the results start to depend on the order the tests run in. The middle option keeps one container and makes isolation explicit with a deterministic reset before each test.

Pitfall: the shared collection has a real cost. xUnit runs the classes of one collection one after another, not in parallel. That is the correct behaviour here, because the classes share one database and would otherwise reset it while another class is using it. But it means you should not put unrelated tests into this collection just for convenience. Tests that do not touch the shared database belong in their own classes outside it, where they can still run in parallel.

Summary

  1. Use IAsyncLifetime for container fixtures: constructors and Dispose cannot await.
  2. Dispose in reverse order and make cleanup unconditional; leaked containers break CI agents.
  3. ICollectionFixture shares one container across many test classes; IClassFixture creates one per class.
  4. The test class's own InitializeAsync runs before every test and is the place for the reset.
  5. A shared collection runs its classes sequentially; keep only tests that need the shared resource in it.