GetContextItem <>()始终为null

时间:2019-02-03 09:14:45

标签: c# .net sitecore glass-mapper

在以下代码中,此行始终返回null:

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

这是课程:

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));
    }
  }
}

在将GlassMapper更新为4.5.0.4和将Jabberwocky更新为3.0.0之前,此方法已经起作用。当我们从Sitecore 8.2升级到9.1时,需要进行这些升级。

1 个答案:

答案 0 :(得分:0)

完全不需要无参数的构造函数。如果您收到类似错误的消息,通常意味着您的依赖项注入不适用于Sitecore控制器。除非您手动注册每个控制器(不太可能),否则应该只拥有要调用的构造函数。

您可以在以下URL上查看依赖项注入的详细信息:http://[instance]/sitecore/admin/showservicesconfig.aspx

如果您未使用默认的SQL statement(例如,如果您使用的是AutoFac或其他工具),则应在配置中显示一个自定义构建器。

有关更多信息,请参见https://doc.sitecore.com/developers/91/sitecore-experience-management/en/dependency-injection.html