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

Sitecore Technical Architect

Bhavik Patel is a certified Sitecore developer who has held Sitecore Most Valuable Professional (MVP) status since 2015. He has more than a decade of experience with enterprise-class Sitecore and Microsoft .NET framework development, including Sitecore integration with SharePoint and Business Intelligence solutions. He leads our Sitecore development practice, engineering enterprise-class Sitecore implementations for Government and commercial sector clients. He's an expert at using Sitecore Helix Framework to create re-usable architectures, streamline the integration of front-end development and provide the foundation for SEO-optimized Sitecore marketing websites.

Explore topics:

Other Blog Posts from Bhavik Patel