Sharing an expensive test resource (such as a SQL Server container) across xUnit test classes with IAsyncLifetime, class, collection and xUnit v3 assembly fixtures, and keeping tests independent with Respawn or unique keys.
Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:
IClassFixture<T>: one instance per test class.ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.[assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.
"Starting a SQL Server container takes something like 5 to 15 seconds, so starting one per test makes the suite unusable. In xUnit the answer is a fixture. I put the container in a class that implements
IAsyncLifetime:InitializeAsyncstarts it and applies migrations, andDisposeAsyncstops it. Then I choose how widely to share it.
IClassFixture<T>gives one instance per test class.ICollectionFixture<T>with a[CollectionDefinition]gives one instance for every class in that collection. xUnit runs collections in parallel but the classes inside one collection serially, so this also stops tests fighting over the same database. In xUnit v3 there is also the assembly fixture: one instance for the whole test assembly, injected into any class that asks for it, while tests keep running in parallel. That's the fastest option, but the fixture has to be thread-safe and tests must not step on each other's data.The mistake I see is people sharing the state along with the resource: test B depends on rows test A inserted, so it passes in the IDE and fails in CI when the order changes. I share the container but every test owns its data. Either it uses unique keys, like a new Guid for the customer, or I reset with Respawn before each test. Respawn deletes rows from every table in foreign-key order but keeps the schema and the
__EFMigrationsHistorytable, and it's far quicker than recreating the database. So: share the expensive thing, isolate the cheap thing."
| Scope | How you declare it | Instances | Parallelism |
|---|---|---|---|
| Per test | Constructor + IAsyncLifetime on the test class |
One per test | Normal |
| Per class | IClassFixture<T> |
One per class | Classes in parallel |
| Per collection | [CollectionDefinition] + ICollectionFixture<T> + [Collection("name")] |
One per collection | Classes in the collection run serially |
| Per assembly (v3) | [assembly: AssemblyFixture(typeof(T))] |
One per run | Tests still run in parallel |
| Technique | How it works | When it fits |
|---|---|---|
| Unique keys | Each test inserts its own rows (new Guid, unique email) and only queries those | Parallel tests on one database; append-only data |
| Respawn | Respawner.ResetAsync deletes all rows except ignored tables before each test |
Tests that count rows or need an empty table; serial collections |
| Transaction rollback | Open a transaction, run the test, roll back | Only when the code under test doesn't manage its own transactions or use several connections |
| Database per class | Create a new database name per class in the same container | Strong isolation without a second container |
If a test changes server-level settings (collation, a database setting, a schema migration test), give it its own container. Sharing only works when the tests treat the resource as a black box.
A typical integration suite of 300 tests that started one container per class (40 classes at about 8 s each) spends around 5 minutes just on start-up. Moving to one collection fixture plus a Respawn reset (about 30 to 50 ms per test) brings that overhead down to under 30 seconds.
Checks whether the candidate knows xUnit's fixture scopes and can trade isolation against speed without creating order-dependent tests.
Green flags
IAsyncLifetime and explains why a constructor won't do.Red flags
xUnit creates a new instance of the test class for every test. That's deliberate: fields on the test class can't leak between tests. Anything that must live longer has to sit outside the test class, in a fixture that xUnit owns and injects through the constructor.
Test run
└─ Assembly fixture (v3) one instance, shared by everything
└─ Test collection runs in parallel with other collections
├─ Collection fixture one instance for the collection
└─ Test class classes inside a collection run one after another
├─ Class fixture one instance for the class
└─ Test method new test class instance per test
Constructors can't be async, and starting a container is I/O. IAsyncLifetime gives xUnit two hooks: InitializeAsync runs (and is awaited) before the first test that uses the fixture, and DisposeAsync runs after the last. In xUnit v3 both return ValueTask, and IAsyncLifetime extends IAsyncDisposable. In v2 they returned Task.
By default every test class is its own collection, and collections run in parallel (up to the number of processor cores by default). Putting classes into one named collection does two things at once: they share the collection fixture, and they run serially. That is often exactly what you want for a database, because two classes truncating the same tables at once would break each other.
v3 added [assembly: AssemblyFixture(typeof(SqlServerFixture))]. Any test class can take SqlServerFixture in its constructor without being in a collection. It's created once per assembly and does not serialise anything, so it suits read-mostly resources, or tests that use unique keys. The fixture is shared state, so anything mutable on it (a counter, a cached HttpClient with changing headers) must be thread-safe.
Respawn (Apache 2.0 licence) reads the database's foreign-key graph once, when you call Respawner.CreateAsync, and builds an ordered list of DELETE statements. ResetAsync runs that list. It doesn't drop tables or rerun migrations, which is why it takes milliseconds. Use TablesToIgnore to keep reference data and __EFMigrationsHistory.
| Action | Typical cost |
|---|---|
| Start a SQL Server container | 5 to 15 s (cold image pull: minutes) |
| Apply EF Core migrations | 0.5 to 3 s |
| Respawn reset | 10 to 100 ms |
| Insert test rows | Single-digit ms |
InitializeAsync. Use it as a class fixture in two classes, then as a collection fixture, and count the log lines.Thread.Sleep(2000) to tests in two classes and time the run with and without a shared [Collection]. Watch parallelism disappear.Customers.Count() == 1. Make them fail together, then fix them with Respawn and with unique keys.EnsureDeletedAsync + MigrateAsync with a Stopwatch.A collection fixture that starts SQL Server once, applies the schema and resets data before each test (xUnit v3, Testcontainers.MsSql, Respawn).
#nullable enable
using Microsoft.Data.SqlClient;
using Respawn;
using Testcontainers.MsSql;
using Xunit;
namespace Orders.IntegrationTests;
// One container for every class in the "SqlServer" collection.
public sealed class SqlServerFixture : IAsyncLifetime
{
private readonly MsSqlContainer _container = new MsSqlBuilder()
.WithImage("mcr.microsoft.com/mssql/server:2022-latest")
.Build();
private Respawner _respawner = null!;
public string ConnectionString => _container.GetConnectionString();
public async ValueTask InitializeAsync()
{
await _container.StartAsync();
// Real projects apply EF Core migrations here; a table keeps the sample self-contained.
await using var connection = new SqlConnection(ConnectionString);
await connection.OpenAsync();
await using var create = new SqlCommand(
"CREATE TABLE Customers (Id uniqueidentifier PRIMARY KEY, Email nvarchar(200) NOT NULL)",
connection);
await create.ExecuteNonQueryAsync();
// Respawn reads the FK graph once; ResetAsync then only runs DELETEs.
_respawner = await Respawner.CreateAsync(ConnectionString, new RespawnerOptions
{
DbAdapter = DbAdapter.SqlServer,
TablesToIgnore = ["__EFMigrationsHistory"]
});
}
public Task ResetAsync() => _respawner.ResetAsync(ConnectionString);
public async ValueTask DisposeAsync() => await _container.DisposeAsync();
}
[CollectionDefinition("SqlServer")]
public sealed class SqlServerCollection : ICollectionFixture<SqlServerFixture>;
[Collection("SqlServer")]
public sealed class CustomerTests(SqlServerFixture db) : IAsyncLifetime
{
// Runs before every test: a clean database, same container.
public async ValueTask InitializeAsync() => await db.ResetAsync();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
[Fact]
public async Task Inserted_customer_is_the_only_row()
{
await using var connection = new SqlConnection(db.ConnectionString);
await connection.OpenAsync(TestContext.Current.CancellationToken);
await using (var insert = new SqlCommand(
"INSERT INTO Customers (Id, Email) VALUES (@id, @email)", connection))
{
insert.Parameters.AddWithValue("@id", Guid.NewGuid());
insert.Parameters.AddWithValue("@email", "[email protected]");
await insert.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
}
await using var count = new SqlCommand("SELECT COUNT(*) FROM Customers", connection);
var rows = (int)(await count.ExecuteScalarAsync(TestContext.Current.CancellationToken))!;
Assert.Equal(1, rows); // Only true because ResetAsync ran first.
}
}
The xUnit v3 alternative: one instance for the whole assembly, and no serialisation.
[assembly: Xunit.AssemblyFixture(typeof(Orders.IntegrationTests.SqlServerFixture))]
// Test classes then take SqlServerFixture in their constructor without [Collection].
// Tests run in parallel, so use unique keys instead of a global Respawn reset.
StartAsync().GetAwaiter().GetResult() in a constructor. Why it is wrong: It ties up a thread and hides start-up exceptions in confusing places. Instead: Implement IAsyncLifetime and await it in InitializeAsync.__EFMigrationsHistory in Respawn. Why it is wrong: The next migration run thinks the database is empty and fails on existing tables. Instead: Add it to TablesToIgnore.The real decision is isolation versus speed, and it's per suite, not per project. I default to one collection per bounded area, each with its own database in a shared container, and Respawn before each test. That gives serial safety inside an area and parallelism across areas. For read-heavy tests against reference data I use an xUnit v3 assembly fixture with no reset at all.
I measure it: the test explorer or the dotnet test TRX report shows time per class. If fixture start-up is more than about 20% of the suite time, widen the scope. If flaky failures appear after widening it, the tests share state and need unique keys.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Class fixture | Few classes, each with very different setup | Start-up × number of classes | More than a handful of classes need the same container |
| Collection fixture + Respawn | Tests that count rows or need empty tables | Serial within the collection; 10 to 100 ms per reset | A huge collection becomes the slowest part of the build |
| Assembly fixture (v3) + unique keys | Large suites; read-mostly or well-isolated data | Fixture must be thread-safe; tests must filter by their own keys | Tests that assert on table-wide counts or truncate |
| Container per test | Tests that change server config or schema | Seconds per test | Anything else |
Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.
Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.
Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.
Last updated 23 Nov 2026.