GetContextItem<>() always null

310 Views Asked by At

In the following code, this line always returns null:

var datasource = GetContextItem<IGlassBase>(inferType: true);

This is the class:

using System.Web.Mvc;
using Jabberwocky.Glass.Models;
using CCO.Feature.Global.Services;
using CCO.Foundation.Multisite.Configuration;
using CCO.Foundation.Mvc.Controllers;
using Jabberwocky.Autofac.Attributes;

namespace CCO.Feature.Global.Areas.CCO.Controllers
{
   public class MetadataController : CCOController
   {
       [AggregateService]
       public interface IDependencies
       {
          IMetadataService MetadataService { get; set; }
          ISitecoreConfigurationManager SitecoreConfigurationManager { get; set; }
       }

    private readonly IDependencies _dependencies;

    public MetadataController(IDependencies dependencies) : base(dependencies?.SitecoreConfigurationManager)
    {
        _dependencies = dependencies;
    }

    public MetadataController() : base() { }

    public virtual ActionResult HtmlPageTitle()
    {
        var datasource = GetContextItem<IGlassBase>(inferType: true);
        var title = _dependencies.MetadataService.GetHtmlPageTitle(datasource);

        return View(new MvcHtmlString(title));
    }

    public virtual ActionResult Metadata()
    {

        var datasource = GetContextItem<IGlassBase>(inferType: true);
        var model = _dependencies.MetadataService.GetPageMetadata(datasource);

        return View(model);
    }

    public ActionResult CustomHeadHtml()
    {
        var datasource = GetContextItem<IGlassBase>(inferType: true);
        var html = _dependencies.MetadataService.GetCustomHeadHtml(datasource);

        return View(new MvcHtmlString(html));
    }
  }
}

This was working before updating GlassMapper to 4.5.0.4 and Jabberwocky to 3.0.0. These upgrades were required when we went from Sitecore 8.2 to 9.1.

1

There are 1 best solutions below

1
Rondel On

A paremeterless constructor should not be required at all. If you're getting an error like that is usually means that your dependency injection is not working for Sitecore Controllers. Unless you're manually registering each controller (unlikely) then you should only have the constructor that you want to be called.

You can see the details of the dependency injection at this URL: http://[instance]/sitecore/admin/showservicesconfig.aspx.

If you aren't using the default serviceProviderBuilder (for instance, if you're using AutoFac or something), you should have a custom builder displaying in your config.

See https://doc.sitecore.com/developers/91/sitecore-experience-management/en/dependency-injection.html for more info