Switch the Context Item

Some times you’ll come across some code which relies on reading the Sitecore.Context.Item and there is no way for you to change this.

This can occur when calling some standard Sitecore pipelines, some custom code which has been inherited without the source etc.

Well, Sitecore API to the rescue.

Introducing the ContextItemSwitcher

I am not sure how long this has been a part of the Sitecore API, but at least since 6.4 where I first noticed it.

Lets say that you want to run the insertRenderings pipeline for another item than the context item (for whatever reason). This code is taken a bit out-of-context in many ways but it serves well as an example.

The first thing the insertRenderings pipeline does in the processor Sitecore.Pipelines.InsertRenderings.Processors.GetItem is to set the InsertRenderingsArgs.Item to the Context.Item.

Using a ContextItemSwitcher when starting the pipeline makes it possible to run the pipeline out of context without having to modify the individual processors. Quite smart,  some might even call it a hidden gem in the Sitecore Api.

 

Anders Laub

Anders Laub Christoffersen

Anders has been working with Sitecore for over a decade and has in this time been the lead developer and architect on several large scale enterprise solutions all around the world. Anders has been nominated a Sitecore Technical MVP three years in a row for 2014, 2015 and 2016. Anders is now working as a Sr. Solutions Architect at Sitecore in Copenhagen.

Leave a Reply

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

*
*
Website