如何使用自定义属性延迟加载属性
本文关键字:属性 延迟加载 自定义属性 何使用 | 更新日期: 2023-09-27 18:27:45
我想使用 Glass Mapper 创建自定义属性来获取 Sitecore 网址,因为无法延迟加载具有SitecoreInfo(SitecoreInfoType.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;
}
}
您可以通过一些创造力和新的委托功能实现与此非常相似的
目标在流畅的配置映射中,类型如下所示:
SitecoreType<IWhatever> sitecoreType = new SitecoreType<IWhatever>();
sitecoreType.Delegate(y => y.Url).GetValue(GetLazyUrl);
private LazyString GetLazyUrl(SitecoreDataMappingContext arg)
{
var item = context.Item;
return new LazyString(
() =>
{
// the necessary actions to get the url
});
}
public class LazyString : Lazy<string>
{
public LazyString(Func<string> valueFactory) : base(valueFactory)
{
}
public override string ToString()
{
return Value;
}
public static implicit operator string(LazyString lazyString)
{
return lazyString.Value;
}
}
它不是一个字符串,但出于许多应用程序的目的,它的行为将类似于一个字符串。