Search code examples
c#sitecoreglass-mapper

How to lazy load a property with custom attribute


I want to create a custom attribute using Glass Mapper for getting the Sitecore URL, because it is not possible to lazy load a property with SitecoreInfo(SitecoreInfoType.Url) and we have some performance issues loading URL of mapped items, where the URL will never be used.

Here is what I've got so far:

The Configuration

public class SitecoreUrlConfiguration : AbstractPropertyConfiguration
{
    public SitecoreInfoUrlOptions UrlOptions { get; set; }

    public bool IsLazy { get; set; }
}

The Attribute

public class SitecoreUrlAttribute : AbstractPropertyAttribute
{
    public SitecoreUrlAttribute()
    {
        this.IsLazy = true;
        this.UrlOptions = SitecoreInfoUrlOptions.Default;
    }

    /// <summary>
    /// Gets or sets a value indicating whether is lazy.
    /// </summary>
    public bool IsLazy { get; set; }

    public SitecoreInfoUrlOptions UrlOptions { get; set; }

    public override AbstractPropertyConfiguration Configure(PropertyInfo propertyInfo)
    {
        var config = new SitecoreUrlConfiguration();
        this.Configure(propertyInfo, config);
        return config;
    }

    public void Configure(PropertyInfo propertyInfo, SitecoreUrlConfiguration config)
    {
        config.UrlOptions = this.UrlOptions;
        config.IsLazy = this.IsLazy;

        base.Configure(propertyInfo, config);
    }
}

The Mapper

public class SitecoreUrlMapper : AbstractDataMapper
{
    public override object MapToProperty(AbstractDataMappingContext mappingContext)
    {
        var context = mappingContext as SitecoreDataMappingContext;
        if (context == null)
        {
            throw new MapperException("Mapping Context is null");
        }

        var item = context.Item;
        var scConfig = this.Configuration as SitecoreUrlConfiguration;

        if (scConfig == null)
        {
            throw new MapperException("SitecoreUrlConfiguration is null");
        }

        var urlOptions = Utilities.CreateUrlOptions(scConfig.UrlOptions);

        urlOptions.Language = null;
        // now, what?
    }
}

So far, so good. But how can I lazy load the URL in the mapper? Does anyone have an idea?


Solution

  • The only way I actually see is to map a Lazy<T> and add a new property to the class which returns the value of this when accessing it. So in you mapper, where you put // now what? I would return the lazy string:

    return new Lazy<string>(() => LinkManager.GetItemUrl(item, urlOptions));
    

    Then in your model, put these two properties:

    [SitecoreUrl]
    public Lazy<string> LazyUrl { private get; set; }
    
    [SitecoreIgnore]
    public virtual string Url
    {
        get
        {
            return this.LazyUrl.Value;
        }
    }