Monday, October 21, 2019

Glass Mapper Upgrade V5

What is needed

Since the release of Glass Mapper 5.0.2, Glass Mapper announced that it will no longer support older versions for errors. Check out here So starting from Sitecore 9, you should upgrade Glass Mapper versions.

How

ISitecoreContext is removed, we have 3 different ones now:
  • IMvcContext
  • IRequestContext
  • IWebFormsContext
Now we have to register all of these services with Sitecore container:
 public class GlassMapperConfigurator : IServicesConfigurator
    {
        public void Configure(IServiceCollection serviceCollection)
        {
            serviceCollection.AddScoped<ISitecoreService>(sp => new SitecoreService(Sitecore.Context.Database));
            serviceCollection.AddScoped<IMvcContext>(sp => new MvcContext(sp.GetService<ISitecoreService>()));
            serviceCollection.AddScoped<IRequestContext>(sp => new RequestContext(sp.GetService<ISitecoreService>()));
            serviceCollection.AddScoped<IGlassHtml>(sp => new GlassHtml(sp.GetService<ISitecoreService>()));
        }
    }

Then, patch this configurator using the following:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <services>
      <configurator type="Foundation.Glass.GlassMapperConfigurator, Foundation.Glass" />
    </services>
  </sitecore>
</configuration>

If you are using Helix(and you should), you can create a foundation project for Glass, add nuget package for your version Glass.Mapper.Sc.{sitecoreVersion} and add service injections there:

public class GlassFactory : IGlassFactory
{
   public ISitecoreService GetSitecoreService() => Sitecore.DependencyInjection.ServiceLocator.ServiceProvider.GetService<ISitecoreService>();
   public IRequestContext GetRequestContext() => Sitecore.DependencyInjection.ServiceLocator.ServiceProvider.GetService<IRequestContext>();
   public IMvcContext GetMvcContext() => Sitecore.DependencyInjection.ServiceLocator.ServiceProvider.GetService<IMvcContext>();
}

We inject Glass services using Sitecore service locator.

In order to use these services in another project(Feature, Foundation etc), you have to first add a reference to your Glass Project. Then, add a nuget package for Glass.Mapper.Sc.{sitecoreVersion}.Mvc and Glass.Mapper.Sc.{sitecoreVersion}.Core. You can use WebForms too, if you want to map items from there.

Then, we can use this factory to get services we want. For instance, if you want to map Item to your class model:

var sitecoreContext = glassFactory.GetSitecoreService();
var mappedItem = sitecoreContext.GetItem<ClassModel>(Item);

If you want to use glass mapper in Controller, inheriting from GlassController is removed. We are using MvcContext instead, ie. getting DataSource item:

var mappedItem = glassFactory.GetMvcContext().GetDataSourceItem<DatasourceClassModel>();

This is the simplest solution, if you want to use Glass mapper in different projects and you have many. 

No comments:

Post a Comment