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)

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

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.

 

   1: public static T Retrieve()
   2: {
   3:     return _unityContainer.Resolve();
   4: }

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

 

   1: public static void InjectStub(I instance)
   2: {
   3:     _unityContainer.RegisterInstance(instance, new ContainerControlledLifetimeManager());
   4: }

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.

   1: _logger = _mockery.CreateMock();
   2:  
   3: ServiceLocator.InjectStub(_logger);

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

Want to learn .net Core?

  • Want to learn .NET Core but don't know where to start?
  • Don't have time to keep up with everything Microsoft is putting out?
  • Stuck on legacy apps when you want to build something new?
Enter your details below and get my weekly update; learn how to build better .NET web apps.
comments powered by Disqus