Dependency Injection using Simple Injector for Sitecore 8 WebApi Attribute Routing in APIControllers

Posted 01/24/2015 by Akshay Sura

I have been working with Simple Injector for a while now, partly because its way faster than Ninject and also because it lands in the top 5 in speed. Simple Injector has very good .NET Support.

There are a few challenges getting WebAPI attribute routing in place in Sitecore 8 with dependency injection using Simple Injector. My Scenario is to communicate with Jive to pull data into a JSON based UI.

First I start of with “Highly testable Sitecore code using MVC, Ninject, Synthesis, Moq, and NUnit” but modified to use Simple Injector. This sets up dependency injection for regular controllers, no problem.

The issue is when you add in APIControllers to the solution. I wasn’t able to get Attribute routing working, worse yet, its different to get it working in Sitecore 7.2, 7.5 and 8. The following posts helped me figure out a solution:

My issue was that I didn’t want to add in configs and overriding pipeline processors. I wanted it to be simple. Based on the blog posts above, I ended up using WebActivatorEx.

Now for my simple APIController with Simple Injector:

The problem was that I got the following error:

I was already registering the Interfaces for Injection in the App_Start for Simple Injector, what else do I need to do?

Since Simple Injector was having an issue I found a few articles on how to resolve this with filters etc but found Simple Injector ASP.NET Web API Integration Quick Start for IIS-hosted applications. By adding the Simple Injector Web API and the following into the App_Start WebActivatorEx code, it started working. 

The thing to note is that we are registering the WebApiRequests.

The results passed back from your APIController are based on the default MediaTypeFormatter. The objects you return as a list, the default media type formatter will handle the serialization based on the content type specified from the client (providing it is json or xml). I didn’t need to do the following since JSON was the default provider:

Here are a few useful links: