Web API Tutorials Part 3 : Translation Abstraction

“We can solve any problem by introducing an extra level of indirection.”

In my experience, this is almost certainly correct, this post will see us adding in an additional layer of Abstraction to allow us to simplify our Controller(s) and manage our Dependencies in a more straightforward manner.

Outcome

Last post saw us implement our Translation PCL into our Web API using Dependency Injection. The problem is that our ITranslator Interface only handles a single Translator Implementation, such that when we inject from our Container we can’t currently translate more than one direction. We’ll look into the why’s shortly, but by the end of the post we will have created :

ITranslatorService Interface;

TranslatorService Implementation and Unit Tests.

Implementation

Why the Abstraction?

We can currently only inject a single ITranslator into our application, which makes extending it problematic (we could use another container that supports instance keys but this is a bit of a hack). So what are our options :

An Interface for each Translator Type;

This is a step backwards as it binds each Controller to a specific Type, let’s rule this out.

A Service that manages our instances of Translators;

Our Controller knows what Direction it wants to translate, the controller name tells us this much, what it doesn’t know is how to do it, this is what gets injected in. A service that takes a Direction, along with the user input and returns the correct translation would meet our requirement.

ITranslatorService

Let’s go with Option 2. What would this service look like? We’ll need to

TranslatorService

It would be nice if our TranslatorService dealt with N-Number of Translation Directions (aside from the fact we’re only interested in two!).

One simple way of implementing this would be to wrap a couple of if statements around a couple of instances of our Translators, but this binds our TranslatorService to specific Translators, which would be undesirable, let’s not do that.

Let’s wrap a few tests around our interface, unfortunately PCL’s referencing Windows 8.1 don’t support Reflection so we can’t use mocking frameworks. It would be good to keep our Translator agnostic of our “actual” Translators, so let’s create a couple of Test Translators.