Xunit does not support any built-in dependency injection features, therefore developers have to come up with a solution to recruit their favourite dependency injection framework in their tests.
This library brings Microsoft's dependency injection container to Xunit by leveraging Xunit's fixture pattern and provides three approaches for dependency injection in your tests:
- 🆕 Property Injection (Recommended) - Clean, declarative syntax using
[Inject]attributes on properties - 🔧 Traditional Fixture-Based - Access services via
_fixture.GetService<T>(_testOutputHelper)(fully backward compatible) - ⚡ Factory Pattern - True constructor injection into service classes (experimental)
- 🎯 Multiple injection patterns - Choose the approach that fits your team's style
- 🔑 Keyed services support - Full .NET 10.0 keyed services integration
- ⚙️ Configuration integration - Support for
appsettings.json, user secrets, and environment variables - 🧪 Service lifetime management - Transient, Scoped, and Singleton services work as expected
- ♻️ Async disposal support - Container-managed
IAsyncDisposableservices are disposed asynchronously during fixture teardown - 📦 Microsoft.Extensions ecosystem - Built on the same DI container used by ASP.NET Core
- 🔓 Parallel-safe fixtures - A shared
TestBedFixturebuilds exactly one container even under xUnit.net v4'sParallelMode.All - 🪢 xUnit.net v4 lifecycle hooks - Fixtures can implement
INotifyTestClassLifecycleAsyncand friends for per-class setup - ⚡ Async fixture initialization - Override
InitializeAsyncCorefor async setup that completes before the container is built - 🔄 Gradual migration - Adopt new features incrementally without breaking existing tests
- 🏗️ Production-ready - Used by Digital Silo and other production applications
- For xUnit packages use Xunit.Microsoft.DependencyInjection versions up to 9.0.5
- For xUnit.v3 3.x packages use Xunit.Microsoft.DependencyInjection versions 9.1.0 – 10.0.5
- For xUnit.v3 4.x packages use Xunit.Microsoft.DependencyInjection version 10.1.0 or later
Also please check the migration guide from xUnit for test authors.
<PackageReference Include="xunit.v3" Version="4.0.0" />
⚠️ xUnit.net v4 requires Microsoft Testing Platform.dotnet testno longer runs v4 test projects through VSTest on the .NET 10 SDK. See Running your tests on xUnit.net v4 for the one-timeglobal.jsonchange you need.
Before you begin, ensure you have:
- .NET 10.0 SDK installed on your development machine
- Visual Studio 2022 or Visual Studio Code with C# extension
- Basic understanding of dependency injection concepts
- Familiarity with xUnit testing framework
First add the following nuget package to your Xunit test project:
Install-Package Xunit.Microsoft.DependencyInjectiondotnet add package Xunit.Microsoft.DependencyInjection<PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="10.1.0" />✨ That's it! All required Microsoft.Extensions dependencies are now automatically included with the package, so you don't need to manually add them to your test project.
Here's a minimal example to get you started quickly:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit.Microsoft.DependencyInjection.Abstracts;
public class MyTestFixture : TestBedFixture
{
protected override void AddServices(IServiceCollection services, IConfiguration? configuration)
=> services
.AddTransient<IMyService, MyService>()
.AddScoped<IMyScopedService, MyScopedService>();
protected override IEnumerable<TestAppSettings> GetTestAppSettings()
{
yield return new() { Filename = "appsettings.json", IsOptional = true };
}
}using Xunit.Microsoft.DependencyInjection.Abstracts;
using Xunit.Microsoft.DependencyInjection.Attributes;
[Collection("Dependency Injection")]
public class MyTests : TestBedWithDI<MyTestFixture>
{
[Inject] private IMyService MyService { get; set; } = null!;
[Inject] private IMyScopedService MyScopedService { get; set; } = null!;
public MyTests(ITestOutputHelper testOutputHelper, MyTestFixture fixture)
: base(testOutputHelper, fixture) { }
[Fact]
public async Task TestMyService()
{
// Your services are automatically injected and ready to use
var result = await MyService.DoSomethingAsync();
Assert.NotNull(result);
}
}[CollectionDefinition("Dependency Injection")]
public class MyTraditionalTests : TestBed<MyTestFixture>
{
public MyTraditionalTests(ITestOutputHelper testOutputHelper, MyTestFixture fixture)
: base(testOutputHelper, fixture) { }
[Fact]
public async Task TestMyService()
{
// Get services from the fixture
var myService = _fixture.GetService<IMyService>(_testOutputHelper)!;
var result = await myService.DoSomethingAsync();
Assert.NotNull(result);
}
}The abstract class of Xunit.Microsoft.DependencyInjection.Abstracts.TestBedFixture contains the necessary functionalities to add services and configurations to Microsoft's dependency injection container. Your concrete test fixture class must derive from this abstract class and implement its single abstract method:
protected abstract void AddServices(IServiceCollection services, IConfiguration? configuration);Everything else is a virtual method with a sensible default, overridden only when needed:
protected virtual IEnumerable<TestAppSettings> GetTestAppSettings(); // JSON files to load; default: none
protected virtual ValueTask InitializeAsyncCore(); // async setup before the container is built; default: no-op
protected virtual ValueTask DisposeAsyncCore(); // async cleanup of fixture-owned resources; default: no-opUse DisposeAsyncCore() to clean up fixture-owned resources (for example, files, sockets, or external clients created by the fixture). Service cleanup for dependencies resolved from the DI container is handled by the framework during async teardown.
TestBedFixture now ignores any TestAppSettings entries whose Filename is null or empty before calling AddJsonFile. That means you can safely return placeholder descriptors or rely only on environment variables; optional JSON files can simply leave Filename blank and the framework skips them automatically when building the configuration root.
GetConfigurationFiles(...) method returns a collection of the configuration files in your Xunit test project to the framework. AddServices(...) method must be used to wire up the implemented services.
Secret manager is a great tool to store credentials, API keys, and other secret information for development purposes. This library has started supporting user secrets from version 8.2.0 onwards. To utilize user secrets in your tests, simply override the virtual method below from the TestBedFixture class:
protected override void AddUserSecrets(IConfigurationBuilder configurationBuilder); There are two method that you can use to access the wired up service depending on your context:
public T GetScopedService<T>(ITestOutputHelper testOutputHelper);
public T GetService<T>(ITestOutputHelper testOutputHelper);To access async scopes simply call the following method in the abstract fixture class:
public AsyncServiceScope GetAsyncScope(ITestOutputHelper testOutputHelper);You can call the following method to access the keyed already-wired up services:
T? GetKeyedService<T>([DisallowNull] string key, ITestOutputHelper testOutputHelper);Available from version 9.2.0 onward: The library supports constructor-style dependency injection while maintaining full backward compatibility with the existing fixture-based approach.
For cleaner test code, inherit from TestBedWithDI<TFixture> instead of TestBed<TFixture> and use the [Inject] attribute:
public class PropertyInjectionTests : TestBedWithDI<TestProjectFixture>
{
[Inject]
public ICalculator? Calculator { get; set; }
[Inject]
public IOptions<Options>? Options { get; set; }
public PropertyInjectionTests(ITestOutputHelper testOutputHelper, TestProjectFixture fixture)
: base(testOutputHelper, fixture)
{
// Dependencies are automatically injected after construction
}
[Fact]
public async Task TestWithCleanSyntax()
{
// Dependencies are immediately available - no fixture calls needed
Assert.NotNull(Calculator);
var result = await Calculator.AddAsync(5, 3);
Assert.True(result > 0);
}
}Use the [Inject("key")] attribute for keyed services:
public class PropertyInjectionTests : TestBedWithDI<TestProjectFixture>
{
[Inject("Porsche")]
internal ICarMaker? PorscheCarMaker { get; set; }
[Inject("Toyota")]
internal ICarMaker? ToyotaCarMaker { get; set; }
[Fact]
public void TestKeyedServices()
{
Assert.NotNull(PorscheCarMaker);
Assert.NotNull(ToyotaCarMaker);
Assert.Equal("Porsche", PorscheCarMaker.Manufacturer);
Assert.Equal("Toyota", ToyotaCarMaker.Manufacturer);
}
}The TestBedWithDI class provides convenience methods that don't require the _testOutputHelper parameter:
protected T? GetService<T>()
protected T? GetScopedService<T>()
protected T? GetKeyedService<T>(string key)- ✅ Clean, declarative syntax - Use
[Inject]attribute on properties - ✅ No manual fixture calls - Dependencies available immediately in test methods
- ✅ Full keyed services support - Both regular and keyed services work seamlessly
- ✅ Backward compatible - All existing
TestBed<TFixture>code continues to work unchanged - ✅ Gradual migration - Adopt new approach incrementally without breaking existing tests
You can migrate existing tests gradually:
- Keep existing approach - Continue using
TestBed<TFixture>with fixture methods - Hybrid approach - Change to
TestBedWithDI<TFixture>and use both[Inject]properties and fixture methods - Full migration - Use property injection for all dependencies for cleanest code
For true constructor injection into service classes, see CONSTRUCTOR_INJECTION.md for the factory-based approach.
Test developers can add their own desired logger provider by overriding AddLoggingProvider(...) virtual method defined in TestBedFixture class.
Your Xunit test class must be derived from Xunit.Microsoft.DependencyInjection.Abstracts.TestBed<T> class where T should be your fixture class derived from TestBedFixture.
Also, the test class should be decorated by the following attribute:
[CollectionDefinition("Dependency Injection")]TestBedFixture implements xUnit.net's IAsyncLifetime, so a fixture can perform asynchronous setup by
overriding InitializeAsyncCore(). xUnit.net awaits it once, after constructing the fixture and before the
first test that uses it runs. Because the service container is built lazily on first use, anything produced
during initialization is available to AddServices:
public sealed class DatabaseFixture : TestBedFixture
{
private PostgreSqlContainer _database = null!;
protected override async ValueTask InitializeAsyncCore()
{
_database = new PostgreSqlBuilder().Build();
await _database.StartAsync(); // runs first
}
protected override void AddServices(IServiceCollection services, IConfiguration? configuration)
=> services.AddSingleton(
new DbOptions(_database.GetConnectionString())); // then this
protected override ValueTask DisposeAsyncCore()
=> _database.DisposeAsync();
}The container does not exist yet while InitializeAsyncCore runs, so services cannot be resolved from
within it - use it to prepare the inputs that AddServices registers. For a full working example, see
AsyncInitTests and Fixtures/AsyncInitFixture.cs in the examples project.
To have managed resources cleaned up, simply override the virtual method of Clear(). This is an optional step.
TestBedFixture performs async teardown and disposes the DI ServiceProvider asynchronously. This ensures container-managed services implementing IAsyncDisposable are disposed correctly during fixture teardown.
If you need additional async cleanup for fixture-owned resources, override DisposeAsyncCore().
As of 10.1.0 it is virtual with a no-op default, so fixtures with nothing to clean up no longer need an empty override:
public sealed class MyTestFixture : TestBedFixture
{
protected override ValueTask DisposeAsyncCore()
{
// Cleanup resources created/owned by the fixture itself.
return ValueTask.CompletedTask;
}
}For a full working example, see AsyncDisposableTests and AsyncDisposableFixture in the examples project.
Version 10.1.0 of this library builds against xunit.v3 4.0.0. Most of your test code carries over unchanged, but the runner and the parallelization model both moved, so read this section before you upgrade.
xunit.v3 4.x runs on Microsoft Testing Platform (MTP) v2, and the .NET 10 SDK no longer bridges MTP
test projects through VSTest. Without any change, dotnet test fails during the build:
error : Testing with VSTest target is no longer supported by Microsoft.Testing.Platform on .NET 10 SDK
and later. If you use dotnet test, you should opt-in to the new dotnet test experience.
Opt in once, per repository, by adding a test section to global.json next to your solution:
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}That is the only change most projects need. Two follow-ups apply if you script dotnet test in CI, because
MTP rejects VSTest-only switches:
| VSTest (xUnit.net v3 3.x) | Microsoft Testing Platform (xUnit.net v4) |
|---|---|
--logger trx |
--report-trx (reference Microsoft.Testing.Extensions.TrxReport) |
--collect "XPlat Code Coverage" (coverlet) |
--coverage (reference Microsoft.Testing.Extensions.CodeCoverage) |
dotnet test MyTests.csproj |
dotnet test --project MyTests.csproj |
The examples project in this repository shows the resulting package set, and azure-pipelines.yml shows the
matching CI configuration.
The headline v4 feature is the ability to run every test in an assembly concurrently, instead of only parallelizing across test collections.
ParallelMode |
Behaviour |
|---|---|
None |
Every test runs sequentially. |
Collections |
Tests in different collections run concurrently; tests inside one do not. Default. |
All |
Every test runs concurrently, regardless of collection or shared fixture. |
The default is unchanged, so upgrading does not alter how your tests are scheduled. To opt in, either set it
in testconfig.json at the root of your test project:
{
"xUnit": {
"parallelMode": "all"
}
}...or declare it in code:
using Xunit.Sdk;
using Xunit.v3;
[assembly: Parallelization(Mode = ParallelMode.All)]TestBedFixture builds its container lazily on first use. As of 10.1.0 that initialization is thread-safe:
however many tests reach the fixture at once, exactly one ServiceProvider is built and every caller gets the
same instance. See ParallelFixtureAccessTests in the examples project for the regression tests covering it.
[Inject] properties and GetService<T>() resolve from the fixture's root container, so a registered
instance is shared by every test that shares the fixture. Under Collections those tests run one at a time and
never observe each other. Under All they run simultaneously, and any service that carries mutable state —
counters, caches, collected output — will interleave across tests.
If you want per-test state, resolve through a scope instead, which hands out a fresh instance per call:
var service = GetScopedService<IMyScopedService>(); // or _fixture.GetAsyncScope(_testOutputHelper)Otherwise, opt the affected scope out of parallelization. Once parallelization is disabled at one layer it cannot be re-enabled below it:
[CollectionDefinition("Dependency Injection", DisableParallelization = true)] // whole collection
public class DependencyInjectionCollection { }
[TestClass(DisableParallelization = true)] // one class
public class MyTests : TestBedWithDI<MyTestFixture> { }
[Fact(DisableParallelization = true)] // one test
public void MyTest() { }v4 lets a fixture observe the assembly, collection, class, method and test lifecycle directly, which is a
natural fit for a TestBedFixture that needs per-class setup beyond its DI registrations:
using Xunit.v3;
public class MyFixture : TestBedFixture, INotifyTestClassLifecycleAsync
{
public ValueTask OnTestClassStartingAsync(IXunitTestClass testClass) => /* per-class setup */ default;
public ValueTask OnTestClassFinishedAsync(IXunitTestClass testClass) => /* per-class teardown */ default;
protected override void AddServices(IServiceCollection services, IConfiguration configuration)
=> services.AddSingleton<IMyService, MyService>();
}Synchronous counterparts (INotifyTestClassLifecycle) and equivalents for the other levels
(INotifyTestAssemblyLifecycle, INotifyTestCollectionLifecycle, INotifyTestMethodLifecycle,
INotifyTestLifecycle, INotifyTestCaseLifecycle, plus ...Async variants) are available too. A working
example lives in Fixtures/LifecycleAwareFixture.cs and LifecycleNotificationTests.cs.
- Test class and method orderers.
ITestClassOrdererandITestMethodOrdererjoin the existing collection and case orderers. Ordering is applied collection → class → method → case. - Generic attributes.
[TestCaseOrderer<TOrderer>],[TestClassOrderer<TOrderer>]and friends replace thetypeof(...)form with a compile-time checked one. - Assertion improvements.
Assert.All/Assert.AllAsynctake athrowIfEmptyargument so an empty collection can be treated as a failure, andAssert.OverrideMaxStringLength,Assert.OverrideMaxEnumerableLength,Assert.OverrideMaxObjectDepthandAssert.OverrideMaxObjectMemberCountlet a single test widen the truncation limits in failure messages. removeAsyncSuffix. AmethodDisplayOptionsvalue that strips theAsyncsuffix from test names.- Native AOT. Test projects can now be published ahead-of-time compiled.
- Retired platforms. MTP v1 and Mono are no longer supported by xUnit.net.
Full details are in the xUnit.net v3 4.0.0 release notes.
The library also has a bonus feature that simplifies running tests in order. The test class does not have to be derived from TestBed<T> class though and it can apply to all Xunit classes.
Decorate your Xunit test class with the following attribute and associate TestOrder(...) with Fact and Theory:
[TestCaseOrderer(typeof(TestPriorityOrderer))]
public class MyOrderedTests
{
[Fact, TestOrder(1)]
public void RunsFirst() { }
[Fact, TestOrder(2)]
public void RunsSecond() { }
}On xUnit.net v4 you can use the generic form instead, which is checked at compile time:
[TestCaseOrderer<TestPriorityOrderer>]
public class MyOrderedTests { }The string-based overload (
[TestCaseOrderer("Type.Full.Name", "AssemblyName")]) was removed in xUnit.net v3 — replace it withtypeof(...)or the generic attribute above.
Ordering only holds while the tests being ordered are not running concurrently. See Full test parallelization below.
This library's TestBedFixture abstract class exposes an instance of IConfigurationBuilder that can be used to support UserSecrets when configuring the test projects:
public IConfigurationBuilder ConfigurationBuilder { get; private set; }📖 Complete Examples Documentation - Comprehensive guide with working code examples
- Live Examples - View the complete working examples that demonstrate all features
- Traditional approach: See examples using
TestBed<TFixture>and_fixture.GetService<T>(_testOutputHelper) - Property injection: See
PropertyInjectionTests.csfor examples usingTestBedWithDI<TFixture>with[Inject]attributes - Factory pattern: See
FactoryConstructorInjectionTests.csfor experimental constructor injection scenarios - Keyed services: See
KeyedServicesTests.csfor .NET 10.0 keyed service examples - Configuration: See
UserSecretTests.csfor configuration and user secrets integration - Async disposal: See
AsyncDisposableTests.csandFixtures/AsyncDisposableFixture.csfor async teardown ofIAsyncDisposableservices - Advanced patterns: See
AdvancedDependencyInjectionTests.csforIOptions<T>,Func<T>, andAction<T>examples - xUnit.net v4 lifecycle hooks: See
Fixtures/LifecycleAwareFixture.csandLifecycleNotificationTests.csfor a fixture that reacts to test class start and finish - Parallel-safe fixtures: See
ParallelFixtureAccessTests.csfor the concurrency guarantees ofTestBedFixture - Async initialization: See
AsyncInitTests.csandFixtures/AsyncInitFixture.csfor async fixture setup viaInitializeAsyncCore
🏢 Digital Silo's unit tests and integration tests are using this library in production.
If you encounter build errors, ensure all required Microsoft.Extensions packages are installed with compatible versions.
- Ensure
appsettings.jsonis set to "Copy to Output Directory: Copy if newer" in file properties - Configuration files must be valid JSON format
- Initialize user secrets:
dotnet user-secrets init - Set secrets:
dotnet user-secrets set "SecretKey" "SecretValue"
- For xUnit packages use Xunit.Microsoft.DependencyInjection versions up to 9.0.5
- For xUnit.v3 3.x packages use Xunit.Microsoft.DependencyInjection versions 9.1.0 - 10.0.5
- For xUnit.v3 4.x packages use Xunit.Microsoft.DependencyInjection version 10.1.0 or later
xUnit.net v4 runs on Microsoft Testing Platform, which the .NET 10 SDK will not launch through VSTest.
Add the test section to global.json as described in
Running your tests on xUnit.net v4.
[Inject] resolves services from the fixture's root container, so stateful services are shared by every
test using that fixture. Resolve through GetScopedService<T>() for per-test state, or disable
parallelization for the affected class with [TestClass(DisableParallelization = true)]. See
Full test parallelization.
- 📖 Complete Examples Documentation - Step-by-step examples for all features
- 🐛 GitHub Issues - Report bugs or request features
- 📦 NuGet Package - Latest releases and changelog
- 📋 Migration Guide - For xUnit.v3 migration