Published on

Using FieldRenderer.Render in the context of a Sitecore job

Authors

The issue

I kept encountering null reference exceptions in some logic where the Sitecore.Web.UI.WebControls.FieldRenderer.Render() method was being used.

It was difficult to identify the issue, as the exception did not specify what was null.

All I got was:

Message: Object reference not set to an instance of an object.. 
StackTrace:    at Sitecore.Web.UI.WebControls.FieldRenderer.RenderField()
at Sitecore.Web.UI.WebControls.FieldRenderer.Render(Item item, String fieldName, String parameters)

Since nothing passed to the method was null, I concluded that the issue might be related to the method being called within the context of a job.

The Clue

Below is a code snippet for some context:

When reviewing the code that executes the job, I noticed that a hardcoded value was being used for SiteName in JobOptions.

Furthermore, this hardcoded value did not match any site names in the Sites configuration in Sitecore.

var jobOptions = new Sitecore.Jobs.DefaultJobOptions("name", 
"categoryName", 
"WrongSiteName", 
implementingType, 
"methodToCall", 
parametersPasedToMethod)
{
    WriteToLog = true
};

var job = new Sitecore.Jobs.DefaultJob(jobOptions);
Sitecore.Jobs.JobManager.Start(job);

Root cause

Sitecore.Web.UI.WebControls.FieldRenderer.Render() depends on a valid Sitecore.Context.

If the third parameter in DefaultJobOptions, "SiteName", does not match any of the configured site names in the Sitecore installation, Sitecore.Context will be null.

Solution

Avoid hardcoding site names in JobOptions. Instead, use a dynamic value like Sitecore.Context.Site.Name to ensure the correct site is referenced.