【问题标题】:know if a particular template in RazorEngine is already compiled or not知道 RazorEngine 中的特定模板是否已经编译
【发布时间】:2013-06-20 18:27:31
【问题描述】:

是否可以知道特定模板是否已经使用 RazorEngine 编译?基本上,如果你打电话:

Razor.Parse("Hello there @Model.Name", model, "hello-world");

这将使用键“hello-world”编译模板。第一次这可能需要几毫秒,但由于缓存,第二次几乎是瞬间。是否可以知道模板是否已经编译?比如:

var isCompiled = Razor.IsCompiled("Hello there @Model.Name", "hello-world");

【问题讨论】:

  • 那只提到缓存是如何完成的。我知道它是如何工作的 - 我需要知道 if 它是否已经被缓存。我基本上需要这个来检测代码中的任何问题,因为多次调用非缓存 Razor 模板实际上会削弱任何应用程序!
  • 但是第一次调用后不会缓存吗?

标签: c# razor razor-2


【解决方案1】:

RazorEngine v3.2.0 包含一个用于检查缓存的ITemplateService.HasTemplate 方法,但该方法在Razor 静态类型上不存在,因此要使用它,您需要手动实例化并维护一个@987654323 @实例。

你真的需要知道它们是否已经被缓存了吗?我问是因为我们在开始解析模板之前会考虑缓存,无论何时您调用ITemplateService.Parse (Razor.Parse)。

【讨论】:

    【解决方案2】:

    从 3.4.1.0 开始,如果模板不在缓存中,Razor.Resolve(templateName) 将返回 null。如果您尝试确定缓存是否包含您发送的文本的特定版本,这可能没有帮助。

    【讨论】:

      【解决方案3】:

      您可以使用以下扩展方法:

      public static class RazorEngineServiceExtensions {
          public static bool IsTemplateCached(this IRazorEngineService service, string name, Type modelType);
      }
      

      一个例子:

      if (!Engine.Razor.IsTemplateCached(templateName, modelType)) {
          Engine.Razor.Compile(templateSource, templateName, modelType);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-31
        • 2011-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-01
        • 1970-01-01
        • 2016-07-29
        • 2017-02-06
        相关资源
        最近更新 更多