Web API Tutorials Part 2 : Translation PCL with Dependency Injection

Portable Class Libraries afford great benefit when it comes to sharing code across platforms/usages. We can share a single library across our UWP App where it’ll run locally and on our Web API where it’ll execute behind our endpoint. Dependency Injection has been made very accessible with the latest ASP.NET MVC Web API.

Outcome

The current MorseCoder.PCL targets only Windows 8.1 as it’s point of API Reference. We’ll need to change that to extend it to the wider .NET Framework (we’re not doing anything prohibitive, so this isn’t a problem). By the end of the post we’ll have updated our PCL to target what we require, and integrated it into the Web API Project using Dependency Injection to pull in an instance of our Translator from the IServiceCollection container.

Dependency Injection

But let’s think about what we’ve done there. Our AlphabetToMorseController knows too much about what it needs to do. We went to the trouble of creating an Interface around our AlphabetToMorseTranslator, but we’re not really using it to our benefit here at all. Wouldn’t it be nice to be able to inject our Translator into the Controller. Fortunately Web API makes it really easy to do this…

There’s a ConfigureServices method on the Startup class that enables us to register our Translator as a Service with the Applications IServiceCollection.

Let’s add the Registration:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton&lt;ITranslator, AlphabetToMorseTranslator&gt;();
}

We’re adding our Interface in along with a reference to AlphabetToMorseTranslator, such that when an instance of Type ITranslator is requested, an AlphabetToMorseTranslator will be returned. (This will be a problem when we implement translation the other way, we’ll cross that bridge when we come to it!)

Let’s wire up our ITranslator Interface to pull an instance out of our Service Collection:

[FromServices]
public ITranslator _translator { get; set; }

Try it!

As in the previous post, hit your endpoint in a Browser and see what happens…