Unit Testing IoC Container Setup in C#
By Harry Bellamy
- 2 minutes read - 302 wordsWhen 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.
A Solution?
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:
using Microsoft.Extensions.DependencyInjection;
...
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddServices(this IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<IDependency1, Dependency1>();
serviceCollection.AddTransient<IDependency2, Dependency2>();
serviceCollection.AddTransient<RequestHandler>();
return serviceCollection;
}
}
The IoC container setup can then be unit tested using a series of tests that follow this pattern:
using Microsoft.Extensions.DependencyInjection;
using Xunit;
...
[Fact]
public void IocContainer_GetService_RequestHandler()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddServices();
var serviceProvider = serviceCollection.BuildServiceProvider();
var service = serviceProvider.GetService<RequestHandler>();
Assert.NotNull(service);
}
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.
Troubleshooting Failures
Were this test to fail, an exception is raised with information detailing the dependencies that couldn’t be resolved.
WebApplication1.Tests.UnitTest1.IocContainer_GetService_RequestHandler
Source: IocContainerTests.cs line 10
Duration: 40 ms
Message:
System.InvalidOperationException : Unable to resolve service for type
'WebApplication1.ApplicationStartup.IDependency2' while attempting to
activate 'WebApplication1.ApplicationStartup.RequestHandler'.
Stack Trace:
...
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.