Mocking Service Fabric & Azure Services with Dependency Injection vs. Inversion of Control (IoC)

In retrospect, in my youth as a software designer I recognize that I often had a preference for the technically elegant. This would sometimes override what was practical from a maintainability standpoint.

I was recently asked about the Dependency Injection approach on a project and why we weren’t using an Inversion-of-Control (IoC) Container such as Unity, Autofac, Ninject, etc. Using an Inversion of Control (IoC) Container is a very elegant approach for centralizing the control of which concrete implementation should be used for a registered interface.

In the case of Service Fabric, our Actors would need to setup and configure an IoC for each container. Then the Actor would go ask the IoC container for the concrete implementation for a given interface. This would create additional complexity for every Actor (we have about 10 actors) in the form of runtime and unit test configuration.

The IoC container approach gives you a lot of flexibility in providing configurability of the container itself allowing interface registrations to be changed at runtime rather than compile time. This is useful if you need this kind of advanced capability due to business or operational reasons but for this project, we really only needed an alternative implementation to be used when unit tests were running.

Given that our requirements were limited to a simple alternative implementation we opted for constructor injection approach. In this approach, we create nullable parameters in the constructors. If the parameter is null, then the default implementation is constructed right inside the Actor. This means that when in production, the Service Fabric framework will initialize the Actor objects and therefore will always have the default implementations initialized. However, in our unit tests, we’re using ServiceFabric.Mocks so here we are able to pass in mock objects into these nullable parameters to swap in MockAzureBlobStorage, MockTwilioService, etc. so that when the unit tests are running they are configured appropriately to have minimal dependencies.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s