When you call RazorEngine.Razor.Compile()
, where is the compiled template stored?
Is it available after the programs been restarted? If there is a memory shortage, will it be dumped?
I am using RazorEngine
in an ASP.NET (MVC) project. Will the precompiled templates be available after the application restarts?
Would it make more sense for me to store them in the HttpContext.Cache
?
If I did, then would it make more sense to use a different function (other than Compile
) that bypasses the internal cache? Is there a way to execute an ITemplate
and just pass it a model?
Does RazorEngine.Razor.Parse()
do any caching? Or is the template recompiled each time?
I've got this to work with RazorEngine 3.4.1.0, installed late Jan 2014.
The key is to call the expensive
Razor.Compile(content, name)
to put the template into cache, then call the cheapRazor.Run(name, model)
to execute the template.Remember that reading template content might be expensive -- say, involving a read from disk -- so my solution only gets template content once. This might be too much caching for you, so careful!
Here's the
RenderPartial
method I use inside a customTemplateBase<T>
subclass. It runs very quickly for multiple calls to the same template.You also need to tell Razor to use this base class
(SqlTempalte<T>)
which you can do like this, by callingRazorEngineConfigurator.Configure()
;Couldn't have done it without this SO answer -- why not give that one an up-vote, too? :)
Edit - If you need to perform caching in a more granular way, you'll need to use a different approach using
RazorEngineTemplateService
andITemplateResolver
.Here's a piece of starter code;
ITemplateResolver
turns template names into template contents, so you can implement, eg, aCachedFileTemplateResolver
which loads cached content from disk.Currently, after the RazorEngine compiles the templates, they are loaded into memory. These assemblies persist in memory only and do not continue beyond the lifetime of the application.
I am considering adding in support for compiling these assemblies to files, but that'll be a future version.
If you call
Razor.Parse
and pass in a name for the template, it will attempt to