How To Easily Add Dependency Injection To Sitecore

Dependency injection and inversion of control are not new concepts, but, it still surprises me how many developers don’t introduce SOLID principles when the costs of failing to do so can be so high. On a recent project (done in web forms by an agency in 2015!!), the code was so tightly bound to the user controls presentation and code behind, that unit testing key aspects of the code were impossible. The company who was looking after the project had no unit tests and this lack of testability actually lost the company a weekend’s worth of leads. If you are working on a project, from experience, if you release code that loses a company money, you will get your ass kicked to the curb. Let’s just say there’s a reason why I’m writing this guide and the agency isn’t!

From my own experience, writing code that adheres to SOLID principles makes my life a lot easier. I can unit test my code to make sure it works, I can use injection to add things like caching, or, security check into my code base without having to update my code.

For those who are still a bit unsure of dependency injection, the concept is pretty simple; instead of using new Object(); in your code base, you pass the needed class/dependencies into the class, via the constructor.

You might wonder how these dependencies get injected into the class… and that is where the dependency injection/inversion of control packages comes into play. There are a number of packages you can get from Nuget that you can add and configure and off you go. Usually, it takes so little time there really is no excuse for not trying it out on your project!

I’ve been using IOC containers for about 6 years and in that time I’ve used StructureMap, Ninject, Castle Windsor which all have their strengths and weaknesses. Unlike some other CMS systems, Sitecore’s API don’t use dependency injection so Sitecore isn’t as tied to an IOC package as other CMS systems. Episerver, for example, uses Structure Map to inject the API’s so on an Episerver project, it makes sense to use it. Recently, I tried working with Simple Injector and as the name implies it is easily the easiest IOC to get started with. It took me less than 10 minutes from first installing it, to get it up and running correctly. In today’s guide, I’m going to cover this process so you can start using dependency injection within your projects.

Installing Simple Injector

In Visual Studio open up Nuget, ‘Tools’ -> ‘NuGet Package Manager’ -> ‘Manage NuGet Packages for Solution’

sitecore_simple_injector

Type in SimpleInjector and you should see the above packages. In my example, I also need my injections to work with Web API and MVC so I installed the extra integration packages ‘WebApi’ and MVC’.

Configuring Simple Injector

This is where life gets stupidly simple to get dependencies working in Sitecore. First, open you global.ascx and find ‘Application_Start’. In here all you need to do is define the following code for MVC

var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
// Register your types
container.Register<IType, MyType>();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterMvcIntegratedFilterProvider();
container.Verify();  // This is optional
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

Web API is also very similar

var container = new Container();
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
// Register your types
container.Register<IType, MyType>();
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();  // This is optional
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);

Compared to a lot of IOC containers, this is so easy;  your code is all in one place without having to add loads of configuration, you can just get on with the task at hand.

Say we have this code:

public interface IType
{
public string Hello { get; set; }
}

With this class

public class MyType : IType
{
public string Hello { get; set; }
}

When we run this code:

public class EnquiryController : ApiController
{
public EnquiryController(IType myType)
{
this.myType= new myType();
}
}

If you tried to run this code, as long as you have the Simple Injector Nuget packages installed and have the container defined in your Global.ascx’s Application_Start, the myType will automatically be populated and you’re free to get on with your work without having to worry about any type of dependencies within your class.

Conclusion

As you can see, adding dependency injection into your projects is so simple with Simple Injector, there really isn’t any excuses to not use it within your project.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *