Implement template caching
masterRazorEngineCore does not provide built-in caching. To avoid the overhead of repeated compilation, implement your own caching mechanism. A common approach is using a ConcurrentDictionary to map template identifiers (like a hash code) to IRazorEngineCompiledTemplate instances.
private static ConcurrentDictionary<int, IRazorEngineCompiledTemplate> TemplateCache = new ConcurrentDictionary<int, IRazorEngineCompiledTemplate>();
private string RenderTemplate(string template, object model)
{
int hashCode = template.GetHashCode();
IRazorEngineCompiledTemplate compiledTemplate = TemplateCache.GetOrAdd(hashCode, i =>
{
RazorEngine razorEngine = new RazorEngine();
return razorEngine.Compile(template);
});
return compiledTemplate.Run(model);
}