Safe Dependency Injection for MVC and WebApi within Sitecore

This post describes how we’ve considered approaching dependency injection with Sitecore at Hedgehog Development.
Many people have posted about dependency injection in Sitecore before, and each has had their own twist.

We’ve noticed that sometimes Sitecore controllers are failing to be resolved when there is a custom Dependency Resolver added.
The problem, as described in Mickey’s first post, is that MVC only allows for one DependencyResolver. So the moment you set your own Dependency Resolver, whatever was set there before (like whatever Sitecore set as the Dependency Resolver) will no longer work.
Because of this, Sitecore’s registered types will no longer get resolved, and you might see the following errors in the logs when you try to access one of the out-of-the-box Sitecore applications.

Exception: Sitecore.Mvc.Diagnostics.ControllerCreationException
Message: Could not create controller: 'Settings'.
The current route url is: 'api/sitecore/{controller}/{action}'. 
Source: Sitecore.Mvc
   at Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext requestContext, String controllerName)

Message: No component for supporting the service Sitecore.Controllers.SettingsController was found

I spoke to Charlie Turano about this, and our solution was to create a ChainedMvcResolver, which will set a ‘Fallback Resolver’ to whatever the resolver was before we came along and set ours.
Read More