Lazy Loading in Glass Mapper

Lazy loading is on-demand loading, when users request the content by Lazy loading then instead of loading the whole content on your page it loads only required content, till further request by users.

Disable Lazy Loading in Glass Mapper:

  1. Individual Get-Item Method
  2. All Sitecore Service Methods

Individual Get-Item Method:

In Sitecore Service Method:

 var item = _service.GetItem<ICustomModel>("/sitecore/content/Home/Course", x=>x.LazyDisabled());  

In MVC Context method:

 var item = _mvcContext.GetDataSourceItem<ICustomModel>(new GetKnownOptions { Lazy = Glass.Mapper.LazyLoading.Disabled});  

All Sitecore Service Methods: If you don't want to pass x.LazyDisabled() in all the GetItem methods then prefer the Generic Class approach.

Create a Generic Class as below:

public class RenderingRepository : IRenderingRepository
 {
    private readonly IMvcContext _mvcContext;

    public RenderingRepository(IMvcContext mvcContext)
    {
        _mvcContext = mvcContext;
    }
    public T GetItem>T<(GetItemOptions options) where T : class
    {
        options.Lazy = Glass.Mapper.LazyLoading.Disabled;
        return _mvcContext.SitecoreService.GetItem>T<(options);
    }
}

Register it into your DI:

serviceCollection.AddTransient>IRenderingRepository, RenderingRepository<();

Now using Controller Constructor DI, you can use this method in your controller Action Result:

public class SampleController : SitecoreController
{
    private readonly IRenderingRepository _renderingRepository;
    public Sample(IRenderingRepository renderingRepository)
    {
        _renderingRepository = renderingRepository;
    }
    public ActionResult Index()
    {
        return View(_renderingRepository.MethodName());
    }
}
Sitecore

Happy Sitecoreing ðŸ˜Š

Comments

Popular posts from this blog

Sitecore Installation Error: Failed to Start Service 'Sitecore Marketing Automation Engine'

Import CSV Data in Sitecore Using PowerShell: Part-3

Sitecore Technology MVP Journey 2022