Xunit.Microsoft.DependencyInjection 9.2.0

dotnet add package Xunit.Microsoft.DependencyInjection --version 9.2.0
                    
NuGet\Install-Package Xunit.Microsoft.DependencyInjection -Version 9.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="9.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Xunit.Microsoft.DependencyInjection" Version="9.2.0" />
                    
Directory.Packages.props
<PackageReference Include="Xunit.Microsoft.DependencyInjection" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Xunit.Microsoft.DependencyInjection --version 9.2.0
                    
#r "nuget: Xunit.Microsoft.DependencyInjection, 9.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Xunit.Microsoft.DependencyInjection@9.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Xunit.Microsoft.DependencyInjection&version=9.2.0
                    
Install as a Cake Addin
#tool nuget:?package=Xunit.Microsoft.DependencyInjection&version=9.2.0
                    
Install as a Cake Tool

Build Status Nuget Nuget

Xunit Dependency Injection framework - .NET 9.0

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 now supports two approaches for dependency injection:

  1. Traditional Fixture-Based Approach - Access services via _fixture.GetService<T>(_testOutputHelper) (fully supported, backward compatible)
  2. Constructor Dependency Injection - Inject services directly into test class properties using the [Inject] attribute (new feature)

Important: xUnit versions

  • For xUnit packages use Xunit.Microsoft.DependencyInjection versions up to 9.0.5
  • For xUnit.v3 packages use Xunit.Microsoft.DependencyInjection versions from 9.1.0

Also please check the migration guide from xUnit for test authors.

Example on how to reference xunit.v3

<PackageReference Include="xunit.v3" Version="2.0.3" />

Getting started

Nuget package

First add the following nuget package to your Xunit project:

Install-Package Xunit.Microsoft.DependencyInjection

Setup your fixture

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 the following two abstract methods:

protected abstract void AddServices(IServiceCollection services, IConfiguration? configuration);
protected abstract IEnumerable<TestAppSettings> GetTestAppSettings();
protected abstract ValueTask DisposeAsyncCore();

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

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); 

Access the wired up services

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);

Accessing the keyed wired up services in .NET 9.0

You can call the following method to access the keyed already-wired up services:

T? GetKeyedService<T>([DisallowNull] string key, ITestOutputHelper testOutputHelper);

Constructor Dependency Injection

New in this version (ver 9.2.0 and beyond): The library now 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);
    }
}

Keyed Services with Property Injection

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);
    }
}

Convenience Methods

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)

Benefits of Constructor Dependency Injection

  • 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

Migration Guide

You can migrate existing tests gradually:

  1. Keep existing approach - Continue using TestBed<TFixture> with fixture methods
  2. Hybrid approach - Change to TestBedWithDI<TFixture> and use both [Inject] properties and fixture methods
  3. Full migration - Use property injection for all dependencies for cleanest code

Factory Pattern (Experimental)

For true constructor injection into service classes, see CONSTRUCTOR_INJECTION.md for the factory-based approach.

Adding custom logging provider

Test developers can add their own desired logger provider by overriding AddLoggingProvider(...) virtual method defined in TestBedFixture class.

Preparing Xunit test classes

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")]
Clearing managed resources

To have managed resources cleaned up, simply override the virtual method of Clear(). This is an optional step.

Clearing managed resourced asynchronously

Simply override the virtual method of DisposeAsyncCore() for this purpose. This is also an optional step.

Running tests in order

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("Xunit.Microsoft.DependencyInjection.TestsOrder.TestPriorityOrderer", "Xunit.Microsoft.DependencyInjection")]

Supporting configuration from UserSecrets

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; }

Examples

  • Please follow this link to view examples utilizing both the traditional fixture-based approach and the new constructor dependency injection features.
  • Traditional approach: See examples using TestBed<TFixture> and _fixture.GetService<T>(_testOutputHelper)
  • Constructor injection: See PropertyInjectionTests.cs for examples using TestBedWithDI<TFixture> with [Inject] attributes
  • Factory pattern: See FactoryConstructorInjectionTests.cs for experimental constructor injection scenarios
  • Digital Silo's unit tests and integration tests are using this library.

One more thing

Do not forget to include the following nuget packages to your Xunit project:

  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Options
  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.Logging
  • Microsoft.Extensions.Configuration.EnvironmentVariables
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Xunit.Microsoft.DependencyInjection:

Package Downloads
Neptunee.xApi

Single line to test your api

XUnitAssured.Net

A tool that helps developers create and maintain test collections with the goal of promoting the development of quality software products.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
9.2.0 69 9/8/2025
9.1.2 3,555 8/16/2025
9.1.1 1,711 8/7/2025
9.1.0 3,290 7/10/2025
9.0.6 1,297 7/6/2025 9.0.6 is deprecated because it has critical bugs.
9.0.5 25,684 5/15/2025
9.0.4 4,844 5/3/2025
9.0.3 10,763 3/25/2025
9.0.2 24,172 3/1/2025
9.0.1 12,136 1/30/2025
9.0.0 16,875 11/23/2024
8.2.2 164,974 9/23/2024
8.2.1 28,745 8/30/2024
8.2.0 54,496 7/9/2024
8.1.1 21,819 6/29/2024
8.1.0 30,275 5/17/2024
8.0.13 27,462 4/6/2024
8.0.12 35,539 2/29/2024
8.0.11 558 2/28/2024
8.0.10 5,195 2/19/2024
8.0.8 26,345 1/19/2024
8.0.7 5,835 1/12/2024
8.0.6 26,004 1/2/2024
8.0.5 2,625 12/21/2023
8.0.4 2,724 12/12/2023
8.0.3 11,189 11/20/2023
8.0.2 841 11/16/2023
8.0.1 849 11/16/2023 8.0.1 is deprecated.
7.0.10 23,216 11/4/2023
7.0.9 1,803 11/2/2023
7.0.8 9,649 10/21/2023
7.0.7 53,428 9/18/2023
7.0.6 36,585 7/8/2023
7.0.5 50,989 3/15/2023
7.0.4 3,770 2/18/2023
7.0.3 34,160 11/20/2022
7.0.2 29,362 11/10/2022
6.2.21 54,452 11/20/2022
6.2.20 784 11/10/2022
6.2.19 3,834 11/1/2022
6.2.18 10,994 10/17/2022
6.2.17 30,561 5/6/2022
6.2.16 1,469 4/27/2022
6.2.15 2,667 4/24/2022
6.2.14 5,317 3/18/2022
6.2.13 1,196 3/9/2022
6.2.12 37,991 2/21/2022
6.2.11 2,036 2/15/2022
6.2.9 5,294 2/8/2022
6.2.8 1,240 2/5/2022
6.2.7 5,126 1/15/2022
6.2.5 1,751 12/24/2021
6.2.4 5,026 11/29/2021
6.2.3 2,222 11/28/2021
6.2.1 921 11/8/2021
6.1.2 769 11/4/2021
6.1.1 1,586 10/27/2021
6.0.1 7,454 10/24/2021
1.0.70 2,706 10/24/2021
1.0.69 10,508 10/17/2021
1.0.68 5,128 8/16/2021
1.0.67 638 8/13/2021
1.0.66 973 7/23/2021
1.0.65 707 7/15/2021
1.0.64 566 7/15/2021
1.0.63 5,802 6/3/2021
1.0.62 659 5/13/2021
1.0.61 654 4/6/2021
1.0.60 2,921 2/27/2021
1.0.59 499 2/15/2021
1.0.58 488 2/15/2021
1.0.57 494 2/15/2021
1.0.56 549 2/10/2021
1.0.55 477 2/9/2021
1.0.54 600 2/4/2021
1.0.53 814 12/29/2020
1.0.52 670 12/27/2020
1.0.51 603 12/4/2020
1.0.50 584 11/30/2020
1.0.0.48 2,259 11/24/2020
1.0.0.47 636 11/18/2020
1.0.0.44 550 11/18/2020
1.0.0.43 558 11/18/2020
1.0.0.42 627 11/18/2020
1.0.0.41 618 11/18/2020
1.0.0.40 587 11/18/2020
1.0.0.39 607 11/18/2020
1.0.0.38 609 11/18/2020
1.0.0.37 598 11/18/2020
1.0.0.36 611 11/18/2020
1.0.0.33 570 11/17/2020
1.0.0.32 556 11/16/2020
1.0.0.31 3,846 11/16/2020