Search code examples
c#unit-testingdependency-injectionbase-class

Where to wire dependency injection for .NET5 test project?


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?


Solution

  • 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>();
            //...
        }
    }