When adding new classes to a C# project I often neglect to add them to the IoC container setup.
This doesn’t sound like much of an issue, but the resulting errors can be difficult to debug, especially when building Azure Function projects.
Adding a unit test or set of unit tests to resolve the necessary dependencies from the IoC container can allow for quicker diagnosis then having to run the application each time a dependency is added.
Unfortunately, the default ASP.Net web application/API template doesn’t allow for the IoC to be easily tested (it suggests putting the IoC configuration in
Startup.cs, which is notoriously difficult to test.)
To allow it to be more easily tested, move the IoC container setup into its own extension method like so:
public static class ServiceCollectionExtensions
public static IServiceCollection AddServices(this IServiceCollection serviceCollection)
The IoC container setup can then be unit tested using a series of tests that follow this pattern:
public void IocContainer_GetService_RequestHandler()
var serviceCollection = new ServiceCollection();
var serviceProvider = serviceCollection.BuildServiceProvider();
var service = serviceProvider.GetService<RequestHandler>();
Due to the transitive nature of dependencies, testing resolving the ‘top-level’ dependencies (i.e. the classes that no other classes are dependent on) provides the most value.
Were this test to fail, an exception is raised with information detailing the dependencies that couldn’t be resolved.
Source: IocContainerTests.cs line 10
Duration: 40 ms
System.InvalidOperationException : Unable to resolve service for type
'WebApplication1.ApplicationStartup.IDependency2' while attempting to
This exception points us directly to the dependency that failed to resolved, rather than trawling through logs or the Visual Studio debug window.
This dependency can then be fixed and the tests rerun.