c# - 在运行时检查 Glass Mapper V3 类型

标签 c# asp.net sitecore sitecore6 glass-mapper

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

相关文章:

c# - Autofac WCF Integration - 根据请求数据解决依赖关系

asp.net - 为什么 aspnet_users 使用 guid 作为 id 而不是递增 int?帮助扩展用户字段的奖励积分

php - 按钮发出 HTTP 请求并将数据存储在数据库中

sitecore 获取 protected 项目列表

sitecore - 在 sitecore 中使用快速查询获取所有子项目和孙项目

Sitecore Droptree 不会排除项目

c# - 使用 MySQL 通过 C# 和 JSON.Net 创建 JSON

c# - 泛型约束有什么用?例如 : where T : IComparable

c# - 以编程方式寻址在 xaml 中创建的 Canvas

c# - 如何在您的 Asp.net 应用程序中获取最新的货币汇率