使用 Glass Mapper V3,是否可以检查 Sitecore 项目是否支持特定的 Glass Mapper 类/接口(interface)?
给定这些类
[SitecoreType]
public partial interface IPage : IGlassBase
{
// ... some properties here ...
}
[SitecoreType]
public partial interface IRateableItem : IGlassBase
{
// ... some properties here ...
}
我想做这样的事情
var context = SitecoreContext();
var item = context.GetCurrentItem<IRateableItem>();
if (item != null)
// it's an item that is composed of the Rateable Item template
不幸的是,如果我这样做,我确实会返回一个 IRateableItem 类型的项目,无论当前项目是否由该模板组成。
最佳答案
丹
另一种解决方案是创建一个在 ObjectConstruction 管道中运行的自定义任务。
像这样:
public class LimitByTemplateTask : IObjectConstructionTask
{
private static readonly Type _templateCheck = typeof (ITemplateCheck);
public void Execute(ObjectConstructionArgs args)
{
if (args.Result != null)
return;
if ( _templateCheck.IsAssignableFrom(args.AbstractTypeCreationContext.RequestedType))
{
var scContext = args.AbstractTypeCreationContext as SitecoreTypeCreationContext;
var config = args.Configuration as SitecoreTypeConfiguration;
var template = scContext.SitecoreService.Database.GetTemplate(scContext.Item.TemplateID);
//check to see if any base template matched the template for the requested type
if (template.BaseTemplates.All(x => x.ID != config.TemplateId) && scContext.Item.TemplateID != config.TemplateId)
{
args.AbortPipeline();
}
}
}
}
public interface ITemplateCheck{}
然后您将更改 IRateableItem 接口(interface),使其具有需要匹配并从 ITemplateCheck 继承的模板 ID:
[SitecoreType(TemplateId = "CF9B175D-872E-439A-B358-37A01155EEB1")]
public interface IRateableItem: ITemplateCheck, IGlassBase{}
最后,您需要在 GlassMapperScCustom 的 CaSTLe IOC 容器中注册新任务:
public static void CastleConfig(IWindsorContainer container){
var config = new Config();
container.Register(
Component.For<IObjectConstructionTask>().ImplementedBy<LimitByTemplateTask>(),
);
container.Install(new SitecoreInstaller(config));
}
我还没有机会对此进行测试,所以如果有任何问题请告诉我。
关于c# - 在运行时检查 Glass Mapper V3 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528470/