Sitecore Pipelines and Unity

This is continuation of my earlier blog post Sitecore MVC and Unity. In that post I discussed how with a minimum effort we can use Unity as the DI Framework for the Sitecore MVC application. In this post, I will discuss how we can use Unity to make the Sitecore Pipelines DI enabled and thus make the Pipelines unit testable.

When it comes to DI for the Sitecore Pipelines, there are two approaches we can take.

  1. Use Sitecore’s inbuilt Configuration Factory. This was described in great detail by Mike Reynolds in his blog Leverage the Sitecore Configuration Factory: Inject Dependencies Through Class Constructors.
  2. Create our own Factory class and use DI container to resolve the objects. This was described in the blog post Sitecore pipelines & commands using IoC containers.

I will be taking the second approach because I can use the same Unity Container that I described in earlier post. For the sake of understanding how this approach works let’s define the application as follows.

Say, I have a website that makes Cookies called CookieMaker. In that, I have a Pipeline called CookieMaker.MakeCookies with some processors. One of the processors is GetSomeFlour. Following is the project structure.

Unity3

The Pipeline Processor GetSomeFlour uses FlourService and the FlourService in turns uses FlourRepository. Here are the classes.

GetSomeFlour

Unity4

FlourService

Unity5

FlourRepository

Unity6

Using Unity container all of the above classes will be resolved. For this, I need to create my own Configuration Factory called UnityContainerFactory as below.

Unity8

In the above class, UnityConfig.GetConfiguredContainer() method returns the same container that was mentioned in my earlier post and since I registered classes by naming convention the Service and Repository classes will be resolved automatically.

To use UnityContainerFactory we need add the following in the config file.

Unity7

That’s all we need to do to make Pipelines DI enabled.

Advertisements

About Himadri Chakrabarti

I am a software developer architect and a Sitecore MVP. My professional interest is everything and anything related to Software Architecture, .NET, Sitecore, Node.js, NoSQL etc. Outside of my profession, I am a hobbyist photographer. Link to my photography site http://himadriphotography.com/
This entry was posted in Framework, MVC, Sitecore and tagged , , . Bookmark the permalink.