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.
- 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.
- 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.
The Pipeline Processor GetSomeFlour uses FlourService and the FlourService in turns uses FlourRepository. Here are the classes.
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.
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.
That’s all we need to do to make Pipelines DI enabled.