In this lesson, you will learn how to write integration tests that verify your Dependency Injection (DI) container is correctly configured to resolve all required services at runtime.
Why Test the Container?
As your application grows, you likely have dozens of services registered with varying lifetimes (Transient, Scoped, or Singleton). A common "silent" failure occurs when a developer adds a new dependency to a constructor but forgets to register the implementation in Program.cs or your Startup class. Because this is a runtime error, the app might compile perfectly but crash immediately when a specific endpoint is hit. Integration tests catch these "missing registration" bugs before they ever reach production.
Implementing the Verification Test
To test your container configuration, you need to spin up an instance of your application’s host within your test project. Using Microsoft.AspNetCore.Mvc.Testing, you can leverage WebApplicationFactory to build the DI container exactly as it exists in production.
The simplest way to verify the configuration is to iterate through your registered services and attempt to resolve them. Here is a compact example:
[Fact]
public void DependencyInjection_Configuration_ShouldResolveAllServices()
{
// Arrange: Create the test host
var factory = new WebApplicationFactory<Program>();
using var scope = factory.Services.CreateScope();
var provider = scope.ServiceProvider;
// Act: Attempt to resolve a critical service
var myService = provider.GetService<IMyBusinessLogic>();
// Assert: Ensure it resolved successfully
Assert.NotNull(myService);
}
Advanced Strategy: Validate the Whole Graph
For mission-critical applications, testing one service isn't enough. You can inspect the IServiceCollection directly before the container is built to verify that specific types are registered, or perform a "deep resolve" by traversing the dependencies of your controllers.
By running this test in your CI/CD pipeline, you treat your DI configuration as code that requires a contract. If a dependency is missing, the test fails during the build phase, preventing the deployment of a broken container.
Key Takeaway: Use integration tests to resolve your dependencies from the production container to ensure no runtime errors exist due to missing or misconfigured service registrations.