This blog post will show you how I setup Simple Injector Dependency Injection in Visual Studio 2015 MVC solution for Sitecore 8.1. I use Simple Injector a lot and is my favorite. I have never had performance issues with it. Hope you enjoy it too.

TIHIDI: Stands for This Is How I Do It. I am going to write a series of blog posts going through how I do Sitecore related work. Hope it helps you!

One of the best ways to install any packages in Visual Studio is to use NuGet Package Manager Console available under the Tools > NuGet Package Manager option. There is a UI available but using the console is the best way for me.

If you are unsure of the command to use, visit www.nuget.org and search for Simple Injector.

Click on the search result and it will show you information on the package.

Now we need to initialize this. There are several ways to initialize Simple Injector, you could use Global.asax or WeActivator but staying true to Sitecore, the best way to do it is to use the Initialize pipeline.

I also want to have access to the ContainerManager for future registration especially when I add Glass models.

Create a new class in the SCExtensions project called ContainerManager. Here is the code for the class.

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

usingSimpleInjector;

namespaceTIHIDI.SCExtensions.DI

{

publicclassContainerManager

{

privatestaticreadonlyContainercontainer=newContainer();

publicContainerContainer

{

get

{

returncontainer;

}

}

}

}

We also want to be able to do Property Injection, create a new class ImportAttributePropertySelectionBehavior in the SCExtensions project. Here is the code for this class.

Now let’s build and deploy this solution. The site loads and we can see our config patch in the showconfig.aspx

If you have any questions or concerns, please get in touch with me. (@akshaysura13 on twitter or on Slack).

UPDATE (7/21/2016): Following Corey Smith‘s comment, I went ahead and implemented the code I usually do. To my surprise it did not work, when I looked into it, I realized that all this while I have been working with Simple Injector versions lower than 3.0. As of Simple Injector 3.0 and above there have been a few API changes which I needed to make. I went ahead and make all appropriate changes for Simple Injector version 3.2. I also looked into my initialization code and realized that it was legacy code from when I started using Ninject a while back. Thanks Corey.

This is a personal blog. Any views or opinions represented in this blog are my own and do not represent those of people, institutions or organizations that the I may or may not be associated with in professional or personal capacity including past, current and future employers, unless explicitly stated.