c# - 如何使用自定义属性延迟加载属性

标签 c# sitecore glass-mapper

我想使用 Glass Mapper 创建自定义属性以获取 Sitecore URL,因为无法使用 SitecoreInfo(SitecoreInfoType.Url) 延迟加载属性,并且我们在加载时遇到了一些性能问题映射项的 URL,永远不会使用该 URL。

这是我到目前为止所得到的:

配置

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

    public bool IsLazy { get; set; }
}

属性

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);
    }
}

映射器

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?
    }
}

到目前为止,还不错。但是我怎样才能在映射器中延迟加载 URL?有人有想法吗?

最佳答案

我实际看到的唯一方法是映射 Lazy<T>并向该类添加一个新属性,该属性在访问它时返回 this 的值。所以在你的映射器中,你把 // now what? 放在哪里我会返回惰性字符串:

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

然后在您的模型中,放入这两个属性:

[SitecoreUrl]
public Lazy<string> LazyUrl { private get; set; }

[SitecoreIgnore]
public virtual string Url
{
    get
    {
        return this.LazyUrl.Value;
    }
}

关于c# - 如何使用自定义属性延迟加载属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26544624/

相关文章:

c# - 如何使用 ASP.NET 或其他方式阻止浏览器关闭?

c# - 捕获组减法/求反

c# - 角色问题

c# - 正则表达式 选择 [A-Z ] 除了两个连续空格

c# - asp :Panel runat ="server" not available in C# . cs 代码页

c# - 使用 Glass Mapper 在 Sitecore View 渲染中使用通用类型

sitecore - 使用 Glass Mapper 在 Sitecore MVC View 中继承模型和渲染参数

c# - 以编程方式删除 Sitecore 中的子布局

sitecore - Sitecore 何时运行初始化管道?

c# - Sitecore GlassMapper 尝试使用查询属性获取没有版本的项目