gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:27:59 28 4
gpt4 key购买 nike

我想使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com