Abstracting your Dependency Injection framework

Published on

I’ve used various Dependency Injection frameworks in the last year or so and have yet to settle on any one in particular.

My focus has been on StructureMap and Microsoft’s Unity (I know I know everyone seems to dislike the latter for some reason but it does have its uses!).

On a couple of occasions I had to switch DI frameworks in the middle of a project. At first this was hard work as I had multiple references to the specific DI framework and had to change them all.

Whilst doing a bit more research I stumbled upon this post which talks about abstracting your DI implementation and it ticked a lot of boxes for me.

The basic idea is to provide methods for interacting with your DI framework and then make sure you reference those methods and not the DI framework directly.

Specifically we’ll need methods to register a type, retrieve the injected instance of a type and pass in mock types for unit testing purposes (for more detail be sure to check out the original post by Nikola Malovic)

public static void Register() where T: I
{
_unityContainer.RegisterType(new ContainerControlledLifetimeManager());
}

The register method simply takes an type definition I (e.g. ILogger) and implementation T (e.g. FileLogger).

In this case I am using Microsoft Unity to register the type but it could be any DI framework.

public static T Retrieve()
{
return _unityContainer.Resolve();
}

The Retrieve method simply returns the injected implementation for the type specified in the parameter (again using MS Unity in this case)

public static void InjectStub(I instance)
{
_unityContainer.RegisterInstance(instance, new ContainerControlledLifetimeManager());
}

Finally the InjectStub method allows us to explicitly pass in an instance of a type (I instance) and have the DI framework use that instance instead of anything we might have registered using the Register method.

This is especially useful when writing unit tests.

_logger = _mockery.CreateMock();
ServiceLocator.InjectStub(_logger);

When running tests following the above code, any calls to ServiceLocator.Retrieve<ILogger> in your code would now use the mocked type.

I know you don't have endless hours to learn ASP.NET

Cut through the noise, simplify your web apps, ship your features. One high value email every week.

I respect your email privacy. Unsubscribe with one click.