私は、これはRazorEngine 3.4.1.0で動作するようになった下旬2014
鍵は、その後、実行に安いRazor.Run(name, model)
を呼び出してキャッシュにテンプレートを置くために、高価なRazor.Compile(content, name)
を呼び出すことですがインストールしましたテンプレート。
テンプレートの内容を読むことは高価になることがあることに注意してください。たとえば、ディスクからの読み取りが必要な場合があります。これはあなたのためにキャッシュがあまりにも多いかもしれないので、慎重に!
私はカスタムTemplateBase<T>
サブクラスの内部で使用するRenderPartial
メソッドです。同じテンプレートへの複数の呼び出しで非常に迅速に実行されます。
public abstract class SqlTemplate<T>: TemplateBase<T>
{
public string RenderPartial(string templateName, object model = null)
{
// loading a template might be expensive, so be careful to cache content
if (Razor.Resolve(templateName) == null)
{
// we've never seen this template before, so compile it and stick it in cache.
var templateContent = GetTemplateContent(templateName);
Razor.Compile(templateContent, templateName);
}
// by now, we know we've got a the template cached and ready to run; this is fast
var renderedContent = Razor.Run(templateName, model);
return renderedContent;
}
private string GetTemplateContent(string templateName)
{
... your implementation here
}
}
また、あなたがRazorEngineConfigurator.Configure()
を呼び出すことによって、次のように行うことができます。この基底クラス(SqlTempalte<T>)
を使用するようにカミソリを伝える必要があります。
public static class RazorEngineConfigurator
{
private static bool configured = false;
public static void Configure()
{
if (configured)
{
return;
}
var templateConfig = new TemplateServiceConfiguration
{
BaseTemplateType = typeof(SqlTemplate<>),
EncodedStringFactory = new RazorEngine.Text.RawStringFactory()
};
RazorEngine.Razor.SetTemplateService(new TemplateService(templateConfig));
configured = true;
}
}
はthis SO answerせずにそれを行っていることができませんでした - なぜ1つにアップ票を与えていない、あまりにも? :)
編集 - あなたはより細かい方法でキャッシングを実行する必要がある場合、あなたはRazorEngineTemplateService
とITemplateResolver
を使用して別のアプローチを使用する必要があります。
ここにスターターコードがあります。
public static RazorEngineTemplateService CreateService(ITemplateResolver resolver, ICollection<string> namespaces)
{
Check.IsNotNull(resolver, "resolver");
var config = new TemplateServiceConfiguration();
config.BaseTemplateType = typeof(PlainTextTemplate<>);
config.EncodedStringFactory = new RazorEngine.Text.RawStringFactory();
config.Resolver = resolver;
config.Namespaces = new HashSet<string>(namespaces);
var service = new RazorEngineTemplateService(config);
return service;
}
ITemplateResolver
、ディスクからキャッシュされたコンテンツをロードCachedFileTemplateResolver
をテンプレートの内容にテンプレート名を回すので、あなたが実装することができ、例えば。
私の質問にお答えしていただきありがとうございます。私はなぜこれを見たことがないのかわかりません。だから、もし私がRazor.Parseに名前を渡すだけで、テンプレートは同じ名前のRazor.Parseという前の時間と同じです。次に、新しいアセンブリを作成する代わりに、キャッシュされたアセンブリを使用しますか? – Rabbi
@Rabbiはい、これは動作する方法です。テンプレートの名前を渡すと、テンプレートコンテンツのハッシュコードを取得し、動的にコンパイルされた型とともにメモリキャッシュに格納します。次に呼び出すときに、テンプレート文字列のハッシュコードが変更されていない場合、テンプレートタイプを自由にインスタンス化して実行することができます。そうでない場合は、キャッシュ内の既存のタイプを無効にして、新しいテンプレートの内容を基に再コンパイルします。 –
参考までに、これは現在のRazorEngineでの動作ではありません。 Profillingは、Razor.Parseが各Web呼び出しで2秒の遅延を引き起こすことを示しました。それをRazor.GetTemplate()で切り替える。 Razor.Run();正しく私たちのキャッシュを引き起こした。 – KallDrexx