Glass.Mapper.Sc Model Configurations(What/When/Why/How)

This blog is based on one of my recent experience where it was required to disable On Demand Loading of Model Configurations in an existing Sitecore 9 application using Glass.Mapper.Sc 5.

Majority of Model configurations in this application were done via Auto mapping and Attribute configurations.

I am sharing here learning I had and some of details regarding the Glass.Mapper.Sc configurations.

Setting Up the Context: Before mentioning the Steps I did for disabling On Demand loading – Let’s understand some details with respect to Model Configurations and their loading details.

What are the available Model Configurations

In Glass.Mapper.Sc – we have 3 ways to configure our mapping Model (Model Configurations)

  1. Automapping
  2. Attribute Configuration
  3. Fluent Configuration

What is On-Demand Loading :
Out of Box – Glassmapper supports On-Demand Loading – which means all the Model configurations will be loaded as and when Model call is made in the application.

Why would we need to disable On-Demand Loading.

  • to ensure all the Model configurations are loaded as part of application startup.
  • Would be handy for any Model Validation during application start up.
  • To avoid referred types being loaded incorrectly.

How to load Model Configurations explicitly:

  • via SitecoreAttributeConfigurationLoader : for Attribute Configurations defined in GlassMapperScCustom.cs
  • via SitecoreFluentConfigurationLoader : for Fluent Configurations defined in GlassMapperScCustom.cs

Steps performed:

  • explicitly set OnDemandMappingEnabled as “false” in App_Start\GlassMapperScCustom.cs
File : App_Start\GlassMapperScCustom.cs

  • Define Attribute Configuration Loader in App_Start\GlassMapperScCustom.cs

File : App_Start\GlassMapperScCustom.cs
  • Make sure all Models(Class/Interface) in the assembly has [SitecoreType] attribute defined.

  • This is required as we sometimes add field level attribute mapping and do not add SitecoreType attribute on Class/Interface.
Attribute Configuration Mapping.
  • In the application I was working had majority of configurations defined via auto-mapping (without any attribute configurations)- So next step was to go in each of such class/Interface and add attribute : [SitecoreType(AutoMap =true)] .

  • Field (which are auto-mapping enabled )- can be left as is.
Auto-Mapping Configuration.
  • Above 2 steps are requied as SitecoreAttributeConfigurationLoader looks for [SitecoreType] attribute while loading the Model configurations during application start up.

  • Without [SitecoreType] defined : class/interface is ignored, even if the properties have attributes defined.

  • The other option is to use Fluent Configurations for mapping Model as using Fluent Configuration ensures Configuration is loaded during application start up.
Fluent Configuration Mapping.

Happy Sitecoring!!

Advertisement