如何在 RazorEngine 中使用相同的密钥在更新的模板上运行编译?

How to RunComplie on updated template using same key in RazorEngine?

string template = "Hello @Model.Name, welcome to RazorEngine!";
var result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });

现在我将现有模板更新为如下所示。我从数据库中获取模板。

string template = "Hello @Model.Name, welcome to My World!";

每当我这样做时,我都会收到错误消息相同的密钥已用于另一个模板

解决此问题的最佳方法是什么?

问题是您没有使用对您传入的模板代码唯一的模板键。RazorEngine 缓存模板并编译它们,因此下一次它会更快 运行.

var helloTemplate = "Hello @Model.Name";

string result;
var model = new { Name = "World" };

//Has the template already been used? If so, Run without compilation is faster
if(Engine.Razor.IsTemplateCached("helloTemplate", null))
{
    result = Engine.Razor.Run("helloTemplate", null, model);
}
else
{
    result = Engine.Razor.RunCompile(helloTemplate, "helloTemplate", null, model);
}