Xunit.DependencyInjection 11.3.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package Xunit.DependencyInjection --version 11.3.2
                    
NuGet\Install-Package Xunit.DependencyInjection -Version 11.3.2
                    
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.DependencyInjection" Version="11.3.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Xunit.DependencyInjection" Version="11.3.2" />
                    
Directory.Packages.props
<PackageReference Include="Xunit.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.DependencyInjection --version 11.3.2
                    
#r "nuget: Xunit.DependencyInjection, 11.3.2"
                    
#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.DependencyInjection@11.3.2
                    
#: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.DependencyInjection&version=11.3.2
                    
Install as a Cake Addin
#tool nuget:?package=Xunit.DependencyInjection&version=11.3.2
                    
Install as a Cake Tool

Xunit.DependencyInjection

Xunit.DependencyInjection NuGet Ask DeepWiki

Use Microsoft.Extensions.DependencyInjection to resolve xUnit test cases: constructor-inject services into your test classes instead of writing them by hand, and reuse the same Startup/host configuration you use in your application.

xUnit v2 users: please use the v2 branch.

Xunit.DependencyInjection.SkippableFact is obsolete on xunit.v3 and no longer needed.

Getting started

Install the NuGet package:

dotnet add package Xunit.DependencyInjection

Add a Startup class to your test project and register your services in ConfigureServices:

namespace Your.Test.Project
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IDependency, DependencyClass>();
        }
    }
}

Then inject IDependency into your test class constructor, exactly like you would with any other DI-enabled class:

public interface IDependency
{
    int Value { get; }
}

internal class DependencyClass : IDependency
{
    public int Value => 1;
}

public class MyAwesomeTests
{
    private readonly IDependency _d;

    public MyAwesomeTests(IDependency d) => _d = d;

    [Fact]
    public void AssertThatWeDoStuff()
    {
        Assert.Equal(1, _d.Value);
    }
}

Xunit.DependencyInjection builds on top of the generic host and fully supports its lifecycle, so you can use any feature the generic host offers, including (but not limited to) IHostedService.

Integrating with ASP.NET Core TestHost (3.0+)

With an ASP.NET Core Startup class

dotnet add package Microsoft.AspNetCore.TestHost
public class Startup
{
    public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
        .ConfigureWebHost[Defaults](webHostBuilder => webHostBuilder
        .UseTestServer(options => options.PreserveExecutionContext = true)
        .UseStartup<AspNetCoreStartup>());
}

With Minimal APIs

If your web project uses Minimal APIs instead of an ASP.NET Core Startup class, install Xunit.DependencyInjection.AspNetCoreTesting:

dotnet add package Xunit.DependencyInjection.AspNetCoreTesting
public class Startup
{
    public IHostBuilder CreateHostBuilder() => MinimalApiHostBuilderFactory.GetHostBuilder<Program>();
}

Your ASP.NET Core project may need to add InternalsVisibleTo for the test project, or add public partial class Program { } at the end of Program.cs, so the test project can reference Program.

See Xunit.DependencyInjection.Test.AspNetCore for a full example.

Startup configuration styles

Startup supports two configuration styles. The Configure method (see Initializing data on startup) is supported by both styles.

HostApplicationBuilder style

  • CreateHostApplicationBuilder method

    If this method is not found, the host falls back to Host.CreateEmptyApplicationBuilder(new() { ApplicationName = assemblyName.Name }).

    public HostApplicationBuilder CreateHostApplicationBuilder([AssemblyName assemblyName]) { }
    
  • ConfigureHostApplicationBuilder method (presence of this method selects the HostApplicationBuilder style)

    public void ConfigureHostApplicationBuilder(IHostApplicationBuilder hostApplicationBuilder) { }
    
  • BuildHostApplicationBuilder method

    If this method is not found, the host is built by simply calling hostApplicationBuilder.Build().

    public IHost BuildHostApplicationBuilder(HostApplicationBuilder hostApplicationBuilder)
    {
        return hostApplicationBuilder.Build();
    }
    

Startup/HostBuilder style

  • CreateHostBuilder method

    public class Startup
    {
        public IHostBuilder CreateHostBuilder([AssemblyName assemblyName]) { }
    }
    
  • ConfigureHost method

    public class Startup
    {
        public void ConfigureHost(IHostBuilder hostBuilder) { }
    }
    
  • ConfigureServices method

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services[, HostBuilderContext context]) { }
    }
    
  • BuildHost method

    If this method is not found, the host is built by simply calling hostBuilder.Build().

    public class Startup
    {
        public IHost BuildHost([IHostBuilder hostBuilder]) { return hostBuilder.Build(); }
    }
    

Method parameters wrapped in [...] above are optional.

How is Startup located?

Startup classes are looked up in the following order; the first match wins.

1. Startup declared on the test class

Apply [Startup(typeof(MyStartup))] on the test class.

2. Nested Startup

public class TestClass1
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services) { }
    }
}

3. Closest Startup in the namespace hierarchy

If the test class's full name is A.B.C.TestClass, Startup is looked up in this order:

  1. A.B.C.Startup
  2. A.B.Startup
  3. A.Startup
  4. Startup

4. Default Startup

A default Startup was required before 8.7.0, and is optional in some cases after 8.7.0. When it's required, add a startup class to your test project as shown above.

By default, Your.Test.Project.Startup, Your.Test.Project is used.

If you want to use a custom Startup, set XunitStartupAssembly and/or XunitStartupFullName in your project's PropertyGroup:

<Project>
  <PropertyGroup>
    <XunitStartupAssembly>Abc</XunitStartupAssembly>
    <XunitStartupFullName>Xyz</XunitStartupFullName>
  </PropertyGroup>
</Project>
XunitStartupAssembly XunitStartupFullName Resulting Startup
Your.Test.Project.Startup, Your.Test.Project
Abc Abc.Startup, Abc
Xyz Xyz, Your.Test.Project
Abc Xyz Xyz, Abc

Running tests in parallel

By default, xUnit runs all test cases within a test class synchronously. This package extends the test framework so tests can run in parallel.

If you register a custom ITestCollectionOrderer, test collections run in the order it specifies, which can be slower than running without one.

Enable it with the ParallelizationMode MSBuild property:

<Project>

  <PropertyGroup>
    <ParallelizationMode></ParallelizationMode>
  </PropertyGroup>

</Project>

This package supports two parallelization policies:

  1. Enhance (or true)

    Respects xUnit's own parallelization behavior.

  2. Force

    Ignores xUnit's parallelization behavior and forces tests to run in parallel.

A test class runs sequentially when it's decorated with [Collection] (unless ParallelizationMode is Force), [CollectionDefinition(DisableParallelization = true)], or [DisableParallelization]. A test method runs sequentially when it's decorated with [DisableParallelization] or [MemberData(DisableDiscoveryEnumeration = true)].

We recommend leaving parallelAlgorithm unset.

Thanks to Meziantou.Xunit.ParallelTestFramework for the inspiration.

Disabling Xunit.DependencyInjection

<Project>
    <PropertyGroup>
        <EnableXunitDependencyInjectionDefaultTestFrameworkAttribute>false</EnableXunitDependencyInjectionDefaultTestFrameworkAttribute>
    </PropertyGroup>
</Project>

Injecting ITestOutputHelper

Inject ITestOutputHelperAccessor instead of ITestOutputHelper directly, since the actual instance is only available while a test is running:

internal class DependencyClass : IDependency
{
    private readonly ITestOutputHelperAccessor _testOutputHelperAccessor;

    public DependencyClass(ITestOutputHelperAccessor testOutputHelperAccessor)
    {
        _testOutputHelperAccessor = testOutputHelperAccessor;
    }
}

Writing Microsoft.Extensions.Logging output to ITestOutputHelper

Install Xunit.DependencyInjection.Logging:

dotnet add package Xunit.DependencyInjection.Logging

The call chain must originate from the running test case; otherwise this feature won't work.

public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services
        .AddLogging(lb => lb.AddXunitOutput());
}

Injecting IConfiguration or IHostEnvironment into Startup

public class Startup
{
    public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
        .ConfigureServices((context, services) => { /* use context.Configuration / context.HostingEnvironment */ });
}

or

public class Startup
{
    public void ConfigureServices(IServiceCollection services, HostBuilderContext context)
    {
        // use context.Configuration / context.HostingEnvironment
    }
}

Customizing IConfiguration

public class Startup
{
    public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
        .ConfigureHostConfiguration(builder => { })
        .ConfigureAppConfiguration((context, builder) => { });
}

How do I inject values with [MemberData]?

[MemberData] members are static and can't be resolved from the container, so use [MethodData] instead — it resolves the referenced method's parameters from DI.

Integrating with OpenTelemetry

Register the Xunit.DependencyInjection activity source with your TracerProviderBuilder to capture the spans this library emits:

TracerProviderBuilder builder;

builder.AddSource("Xunit.DependencyInjection");

Running code before and after each test

Inherit from BeforeAfterTest and register your implementation as a BeforeAfterTest service.

See the sample.

Initializing data on startup

For synchronous initialization, use the Configure method. For asynchronous initialization, use an IHostedService.

Package Description
Xunit.DependencyInjection.Logging Write Microsoft.Extensions.Logging output to ITestOutputHelper, see above
Xunit.DependencyInjection.AspNetCoreTesting Integration with ASP.NET Core Minimal API TestHost, see above
Xunit.DependencyInjection.StaFact Run [StaFact]/[StaTheory] test cases on an STA thread (e.g. for UI tests)
Xunit.DependencyInjection.xRetry Support xRetry's [RetryFact]/[RetryTheory]
Xunit.DependencyInjection.FsCheck Support FsCheck property-based [Property] tests
Xunit.DependencyInjection.Demystifier Use Ben.Demystifier to format exception stack traces
Xunit.DependencyInjection.Analyzer Roslyn analyzer that validates Startup class shape at compile time
Xunit.DependencyInjection.Template dotnet new xunit-di template to scaffold a new test project

StaFact

dotnet add package Xunit.DependencyInjection.StaFact
public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services.AddStaFactSupport();
}
public class MyStaTests
{
    [StaFact]
    public void RunOnStaThread() { }

    [StaTheory]
    [InlineData(1)]
    public void RunOnStaThread(int value) { }
}

xRetry

dotnet add package Xunit.DependencyInjection.xRetry
public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services.AddXRetrySupport();
}
public class MyRetryTests
{
    [RetryFact(3)]
    public void FlakyTest() { }
}

FsCheck

dotnet add package Xunit.DependencyInjection.FsCheck
public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services.AddFsCheckSupport();
}

Demystifier

dotnet add package Xunit.DependencyInjection.Demystifier
public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services.UseDemystifyExceptionFilter();
}

Analyzer

The analyzer is automatically added as an analyzer reference when you install Xunit.DependencyInjection, and reports compile-time diagnostics (e.g. multiple Startup constructors, invalid Configure* method signatures) so misconfigured Startup classes are caught early.

Project template

dotnet new install Xunit.DependencyInjection.Template
dotnet new create xunit-di -n MyTestProject

See Xunit.DependencyInjection.Template for details.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  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. 
.NET Framework net472 is compatible.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (13)

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

Package Downloads
Rystem.Test.XUnit

Rystem is a open-source framework to improve the System namespace in .Net

Xunit.DependencyInjection.Logging

Support Microsoft.Extensions.Logging to ITestOutputHelper. public void Configure(IServiceProvider provider) { XunitTestOutputLoggerProvider.Register(provider); }

Xunit.DependencyInjection.SkippableFact

Support Xunit.SkippableFact. public void ConfigureServices(IServiceCollection services) { services.AddSkippableFactSupport(); }

Xunit.DependencyInjection.xRetry

Support xRetry. public void ConfigureServices(IServiceCollection services) { services.AddXRetrySupport(); }

Xunit.DependencyInjection.Demystifier

Use Ben.Demystifier Formate Exception. public void ConfigureServices(IServiceCollection services) { services.UseDemystifyExceptionFilter(); }

GitHub repositories (19)

Showing the top 19 popular GitHub repositories that depend on Xunit.DependencyInjection:

Repository Stars
dotnetcore/Util
Util是一个.Net平台下的应用框架,旨在提升中小团队的开发能力,由工具类、分层架构基类、Ui组件,配套代码生成模板,权限等组成。
chromelyapps/Chromely
Build Cross Platform HTML Desktop Apps on .NET using native GUI, HTML5, JavaScript, CSS, Owin, AspNetCore (MVC, RazorPages, Blazor)
microsoft/kernel-memory
Research project. A Memory solution for users, teams, and applications.
Nexus-Mods/NexusMods.App
Home of the development of the Nexus Mods App
dotnetcore/sharding-core
high performance lightweight solution for efcore sharding table and sharding database support read-write-separation .一款ef-core下高性能、轻量级针对分表分库读写分离的解决方案,具有零依赖、零学习成本、零业务代码入侵
wabbajack-tools/wabbajack
An automated Modlist installer for various games.
bing-framework/Bing.NetCore
Bing是基于 .net core 3.1 的框架,旨在提升团队的开发输出能力,由常用公共操作类(工具类、帮助类)、分层架构基类,第三方组件封装,第三方业务接口封装等组成。
kendryte/nncase
Open deep learning compiler stack for Kendryte AI accelerators ✨
luoyunchong/lin-cms-dotnetcore
😃A simple and practical CMS implemented by .NET + FreeSql;前后端分离、Docker部署、OAtuh2授权登录、自动化部署DevOps、自动同步至Gitee、代码生成器、仿掘金专栏
kodlamaio-projects/nArchitecture
Inspired by Clean Architecture, nArchitecture is a monolith project which uses advanced techniques.
ShokoAnime/ShokoServer
Repository for Shoko Server.
sethreno/schemazen
Script and create SQL Server objects quickly
grate-devs/grate
grate - the SQL scripts migration runner
BestOwl/MyPhone
Connect your mobile devices (Android/iOS/WindowsPhone) to PC
WeihanLi/WeihanLi.Npoi
NPOI Extensions, excel/csv importer/exporter for IEnumerable<T>/DataTable, fluentapi(great flexibility)/attribute configuration
Viincenttt/MollieApi
This project allows you to easily add the Mollie payment provider to your application.
2sic/2sxc
DNN + 2sxc = #DNNCMS - This tool helps web designers and developers prepare great looking content in DNN (DotNetNuke). It's like mixing DNN with Umbraco and Drupal :)
sa-es-ir/DotNet.RateLimit
A Distributed RateLimit for Controller-Actions and Minimal API.
dr-marek-jaskula/DomainDrivenDesignUniversity
This project was made for tutorial purpose - to clearly present the domain driven design concept.
Version Downloads Last Updated
12.0.0 457 8/22/2026
11.3.2 140 8/21/2026
11.3.1 13,218 8/12/2026
11.3.0 140,426 6/9/2026
11.2.1 362,851 3/18/2026
11.2.0 503,093 2/27/2026
11.1.1 321,672 12/30/2025
11.1.0 323,859 11/11/2025
11.0.0 191,191 9/21/2025
10.8.0 14,760 9/21/2025
10.7.0 22,046 9/3/2025
10.6.0 127,621 7/16/2025
10.5.0 27,718 6/16/2025
10.4.2 812,809 5/18/2025
10.4.1 28,457 5/7/2025
10.4.0 348,293 4/9/2025
10.3.0 144,195 3/10/2025
9.9.2 69,608 3/18/2026
9.9.1 383,975 5/7/2025
Loading failed

Use Microsoft.Extensions.DependencyInjection to inject xunit testclass. If you want write Microsoft.Extensions.Logging to ITestOutputHelper, please install Xunit.DependencyInjection.Logging.

Release notes:

11.3: Support FsCheck.Xunit.v3.
11.2: Update xunit.v3 to 3.2.2, Move HostManager.Start/Stop to AssemblyRunner.
11.1: Update xunit.v3 to 3.2.0.
11.0: C# 14, Downgrade Microsoft.Extensions.Hosting to 8.0.
10.8: Add CreateHostApplicationBuilder method.
10.7: Update xunit.v3 to 3.0.1, does not set ApplicationName if it is already configured.
10.6: Update xunit.v3 to 3.0.0.
10.5: Improve compatibility with top level statements.
10.4: Fix #146.
10.3: Update xunit.v3 to 2.0.0.
10.2: Fix some parallelization problem.
10.1: Allow the default startup to be missing anywhere.
10.0: Upgrade xunit to v3.