GlassMapper and Remote Events

Posted by Bhavik Patel on 12/27/2016

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!


Looking for a partner who will exceed your expectations? Get in touch.

SYMSOFT SOLUTIONS 4090 Truxel Road, Suite 200 Sacramento, CA 95834
United States (916) 567-1740