How to check DI container in ASP.NET Core?

In my class, StartupI use a method ConfigureServices(IServiceCollection services)to configure my service container using the built-in DI container from Microsoft.Extensions.DependencyInjection.

I want to check the dependency graph in unit test to verify that all services can be constructed so that I can fix any services that are missing during unit testing, instead of the application crashing during application execution. In previous projects, I used Simple Injector, which has a method .Verify()for the container. But I could not find anything like it for ASP.NET Core.

Is there a built-in (or at least recommended) way to verify that you can build an entire dependency graph?

(The stupidest way I can think of is something like this, but it will still fail due to open generics that are introduced by the framework itself):

startup.ConfigureServices(serviceCollection);
var provider = serviceCollection.BuildServiceProvider();
foreach (var serviceDescriptor in serviceCollection)
{
    provider.GetService(serviceDescriptor.ServiceType);
}
+6
source share
1 answer

To ensure that your ASP.NET Core application is working properly and that all dependencies are entered correctly, you should use ASP.NET Core Integration Testing . This way you can initialize TestServerwith the same class Startup, so it forces all dependencies to be entered (without layouts or similar stubs) and test your application using open routes / urls / paths.

URL :

public class PrimeWebDefaultRequestShould
{
    private readonly TestServer _server;
    private readonly HttpClient _client;
    public PrimeWebDefaultRequestShould()
    {
        // Arrange
        _server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
        _client = _server.CreateClient();
    }

    [Fact]
    public async Task ReturnHelloWorld()
    {
        // Act
        var response = await _client.GetAsync("/");
        response.EnsureSuccessStatusCode();

        var responseString = await response.Content.ReadAsStringAsync();

        // Assert
        Assert.Equal("Hello World!", responseString);
    }
}
+1

All Articles