Sitecore Upgrade to 10.2 - GlassMapper upgrade from 4 to 5

Sitecore Upgrade to 10.2 - GlassMapper upgrade from 4 to 5

By admin February 23, 2024

SitecoreContext

SitecoreContext is no longer available in GlassMapper 5+ and need to be replaced with MvcContext (used mainly in Controllers) or RequestContext (used outside Controllers).

So for every piece of code

private readonly ISitecoreContext _sitecoreContext

should be changed to

private readonly IRequestContext _sitecoreContext;

or

private readonly IMvcContext _sitecoreContext;

Note that GetItem method and etc need to be called from SitecoreService.

_sitecoreContext.GetItem<Item>("{8A1AC22A-EADC-46CE-9954-88BB2680AB83}")

should be changed to

_sitecoreContext.SitecoreService.GetItem<Item>("{8A1AC22A-EADC-46CE-9954-88BB2680AB83}")

Another example is where in the class method the SitecoreContext is initialized

For example

var context = new SitecoreContext();

need to be changed to

var context = new RequestContext(new SitecoreService(Sitecore.Context.Database)).SitecoreService;

GetHomeItem

_sitecoreContext.GetHomeItem<ISiteRoot>();

will be changed to

 context.SitecoreService.GetItem<ISiteRoot>(Sitecore.Context.Site.StartPath)

GlassView is obsolete

All views need to be updated as follow:

@inherits Glass.Mapper.Sc.Web.Mvc.GlassView<MyNamespace.MyViewModel>

 @Editable(Model, x => x.Item.Title)

to

@model MyNamespace.MyViewModel
@Html.Glass().Editable(Model, x => x.Item.Title)

GetCurrentItem

The new version GetCurrentItem is marked obsolete and replaced by GetContextItem method

 Item = _sitecoreContext.GetCurrentItem<MyModel>()

should be changed as follow, note that _sitecoreContext is now IMvcContext

 Item = _sitecoreContext.GetContextItem<MyModel>()

Featured Blogs