GlassMapper and Remote Events

Bhavik Patel • 12/27/2016

Sitecore remote events and Glassmapper

As I was working on a project recently, I realized that when using GlassMapper in events that are triggered remotely (in my case, the publish:end:remote event), I was getting a fairly odd error that looked like this:

Failed to map to property '<Property Name>' on type '<Class Name>'

It was also odd that the NullReferenceException was coming from Sitecore.Kernel, so that prompted me to do some digging via decompilation. It so turns out that for Rich Text fields, GlassMapper actually attempts to invoke the “renderField” Sitecore pipeline method in order to get the correct string that needs to be assigned to the property that is mapped to the Rich Text field. This is fine and dandy when you’re working with GlassMapper in the context of your site, but not so well in remotely triggered events, in which there is no Site context.

After some searching, it turns out not all is lost. You can wrap your GlassMapper related code in an instance of Sitecore’s SiteContextSwitcher object, which will allow that code to execute within a Site context. See below:

using (new Sitecore.Sites.SiteContextSwitcher(Sitecore.Sites.SiteContext.GetSite("website")))
    // Do your GlassMapper stuff here

The “Sitecore.Sites.SiteContext.GetSite()” method retrieves the appropriate site from configuration, so if your site name is not “website” you can adjust the code above appropriately. Also, if you are dealing with multiple sites and need remote events to handle that as well, you’ll have to modify the logic above so that you take each site’s context into consideration in the remote event.

Happy Remote Eventing!

Bhavik Patel

Bhavik is a .NET developer with over 9 years of experience, focusing on Sitecore CMS for the last 3 years. He has worked on several Sitecore CMS projects in both single-site and multi-site scenarios, and truly enjoys how extensible it is. He has a passion for problem solving and using technology to create engaging websites and applications. Bhavik is a Sitecore Technology MVP, 2015 and 2016.

Explore topics:

Other Blog Posts from Bhavik Patel

Subscribe for insights, trends and big ideas