Home > Back-end >  Where to wire dependency injection for .NET5 test project?
Where to wire dependency injection for .NET5 test project?

Time:10-26

I have a test project testing various parts of a large 13 project solution. A lot of these tests require database access (wired to a test DB) and numerous services to work. Currently all my test classes inherit from a common BaseTest class which registers DI by calling the following code in the BaseTest constructor :

public IHostBuilder CreateHostBuilder(string[] args = null) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog()
        .ConfigureServices((hostContext, services) =>
        {
            //Omitted for brevity

            _mediator = _provider.GetService<IMediator>();
        });

This works perfectly but I suspect it's needlessly being called by every test class. Is there an equivalent to Program.cs or some sort of way the test project could call this code ONCE? Where can I move this code to from the base constructor to achieve this?

CodePudding user response:

I ended up switching to XUnit. Much more feature-rich and the xUnit.DependencyInjection nuget package supports dependency injection directly with Startup.cs as we are used to and picks it right up with no additional configuration :

public class Startup
{
    public static void ConfigureHost(IHostBuilder hostBuilder)
    {
        hostBuilder.UseSerilog();
    }

    public static void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ISomeService, SomeService>();
        //...
    }
}
  • Related