Monday, October 2, 2017

Sitecore custom dependency injection breaks after upgrade to 8.2

During an upgrade from version 8.1 to 8.2 of Sitecore, custom dependency injection (Autofac) stopped working after the updated custom code was deployed. Trying to resolve anything would simply return a null and cause the code to break.

It turns out that application start in Sitecore 8.2 has been made internal, which meant the instantiation of this project's dependency injection was not be called. Best practice for Sitecore is not to use App_Start and instead to use the initialize pipeline, as shown below.

The initialize pipeline code:
 
using Sitecore.Pipelines;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MyProject
{
    public class RegisterContainer : Sitecore.Mvc.Pipelines.Loader.InitializeRoutes
    {
        public override void Process(PipelineArgs args)
        {
            // App Start code here
        }
    }
}
The initialize pipeline patch file:
 
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
      <pipelines>
          <initialize>
              <processor type="MyProject.RegisterContainer, MyProject"
                          patch:before="*[@type='Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc']" />
          </initialize>
      </pipelines>
  </sitecore>
</configuration>

No comments:

Post a Comment