Open bnuzhouwei opened 5 years ago
See the docs for TemplateManager and Caching.
I read the document calfully, and searched Use external cache provider for RazorEngine #278 and Redis support #352, but still get no idea. Does any succeed in share cache in multiple applications by cache templates to disk, redis, or memcache, thanks.
I'm also having this problem with the cost of the first run. All my attempts to cache the template beforehand have failed. Any insights would be much appreciated.
Thanks, everyone.
I compile the template at application startup time (in my case, a Windows service, so I add it as part of the OnStart
functionality):
var templateFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates");
foreach (var templateFile in Directory.EnumerateFiles(templateFolder, "*.cshtml"))
{
var template = new FileInfo(templateFile);
try {
Engine.Razor.Compile(template.Name);
}
catch (TemplateCompilationException ex) {
Console.WriteLine($"Could not pre-compile template {template.Name}", ex);
}
}
That compiles all the templates found in the named folder; then when it comes time to use them, I just use the .Run
method:
public void RenderContent(string templateName, object model) {
return Engine.Razor.Run(templateName, null, model);
}
As long as templateName
matches the value I used for template.Name
when compiling, then everything works as it should.
The RunCompile cost much time on the first runs, and the second time is much faster: i.e. I run a template on Rasp PI 3B+, it cost 5597ms on the first run, but only 47ms on the second run. Is it possible cache the compile result to disk and read from the disk if the template is not changed.