RazorEngine不缓存编译模板

本文关键字:编译 缓存 RazorEngine | 更新日期: 2023-09-27 17:53:41

目前,我正在使用RazorEngine v2.1作为发送模板电子邮件(成千上万)的后台进程的一部分。为了加快速度,模板以其md5和作为名称进行编译。这使得当模板被更改时,它被重新编译,并且使用该模板的所有电子邮件都能够使用相同的编译模板。我在列表中跟踪已编译模板的名称,以便我知道何时再次调用compile(以及做一些其他事情)。

问题:在我看来,经过很长时间和大量的模板修改后,所有这些缓存编译的模板可能仍然在内存中,因为它看起来像它们被存储在dynamic中。对于这个特殊的进程,它可能一次运行几个月而不重新启动,如果所有以前版本的模板仍然存在,这可能会造成严重的内存泄漏。

问题:是否有一种方法来取消缓存旧模板,使它们不再挂在dynamic ?

例如,如果我能够自己保存已编译的模板对象,并在我想使用它们时将它们传递给RazorEngine,我可以决定何时将它们丢弃,这将消除内存泄漏。然而,如果RazorEngine已经有了解决这个问题的方法,那么知道这一点也会很方便,因为我在互联网上找不到很多关于这个特定问题的参考资料。有很多关于为什么应该使用编译模板来减少内存使用的事情,但是我很难找到任何关于大量未使用的编译模板在长寿命应用程序中积累的事情。

编辑:我刚刚读了一点关于缓存是如何工作的,如果相同的名字传递在一个不同的模板,它将重新缓存它,并丢弃旧的。然而,这里的问题仍然存在,因为随着时间的推移,电子邮件将被添加和删除,并且随着时间的推移,所有旧的被删除的电子邮件将仍然存在(即使它不会存储每个版本的模板的副本)。

RazorEngine不缓存编译模板

回答这个问题,因为它似乎仍然与某些人有关。(https://github.com/Antaris/RazorEngine/issues/232 # issuecomment - 128802285)

对于这个特殊的进程,它可能一次运行几个月而不重新启动,如果所有以前版本的模板仍然存在,这可能会造成严重的内存泄漏。

当您更改和重新编译模板时,您会有内存泄漏,因为您无法卸载已加载的程序集(RazorEngine在后台为您编译和加载)。

真正释放内存的唯一方法是重新加载AppDomain或重启进程。

其他答案似乎在谈论新版本,以防止默认配置中的内存泄漏(使您意识到这个问题),并需要一些自定义配置,以便能够用另一个模板代码重新编译密钥。请注意,所有其他答案实际上都将增加内存消耗!

matthid,一个RazorEngine贡献者

我最近升级到最新的稳定版本RazorEngine(3.6.1),由于所有的变化,我的缓存清理策略不再工作。很多东西已经改变了,这个项目的文档不仅过时了,而且是从作者的角度写的,这使得用户体验很差。

这是我使用3.6.1清除所有缓存模板的当前代码。

public static class TemplateManager
{
    static IRazorEngineService Service { get; set; }
    static TemplateServiceConfiguration Configuration { get; set; }
    static TemplateManager()
    {
        Configuration = new TemplateServiceConfiguration()
        {
            // setting up our custom template manager so we map files on demand
            TemplateManager = new MyTemplateManager()
        };
        Service = RazorEngineService.Create(Configuration);
        Engine.Razor = Service;
    }
    /// <summary>
    /// Resets the cache.
    /// </summary>
    public static void ResetCache()
    {
        Configuration.CachingProvider = new RazorEngine.Templating.DefaultCachingProvider();
    }
    /// <summary>
    /// Compiles, caches and parses a template using RazorEngine.
    /// </summary>
    /// <param name="templateType">Type of the template.</param>
    /// <param name="anonymousType">Type of the anonymous object.</param>
    /// <param name="cachedEnabled">true to enabled caching; false otherwise</param>
    /// <returns></returns>
    public static string GetTemplate<T>(EmailTemplateType templateType, T anonymousType, bool cachedEnabled = true)
    {
        string templateName = templateType.ToString();
        if (cachedEnabled == false)
            ResetCache();
        // pre-compile, cache & parse the template
        return Engine.Razor.RunCompile(templateName, null, anonymousType);
    }
}
public enum EmailTemplateType
{
    ForgotPassword,
    EmailVerification
}
public class MyTemplateManager : ITemplateManager
{
    public ITemplateSource Resolve(ITemplateKey key)
    {
        string file = HttpContext.Current.Server.MapPath(string.Format("~/EmailTemplates/{0}.cshtml", key.Name));
        return new LoadedTemplateSource(System.IO.File.ReadAllText(file), file);
    }
    public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
    {
        return new NameOnlyTemplateKey(name, resolveType, context);
    }
    public void AddDynamic(ITemplateKey key, ITemplateSource source)
    {
        throw new NotImplementedException("dynamic templates are not supported!");
    }
}

这是Asp中代码的一个示例用法。Net MVC:

var emailBody = TemplateManager.GetTemplate(EmailTemplateType.ForgotPassword, new
{
    SiteUrl = Url.Action(MVC.Home.Index(), protocol: Request.Url.Scheme),
    SiteFriendlyName = SiteSettings.Instance.DomainName.FriendlyName,
    PasswordResetLink = Url.Action(MVC.Account.ActionNames.ResetPassword, MVC.Account.Name, new { userId = user.Id, code = code }, protocol: Request.Url.Scheme),
    NotRequestedUrl = Url.Action(MVC.Account.ActionNames.PasswordResetNotReqeuested, MVC.Account.Name, new { userId = user.Id, requesterIpAddress = WebUtils.GetClientIPAddress(), code = code }, protocol: Request.Url.Scheme)
},
/* this setting allows me to disable caching during development */
!SiteSettings.Instance.EmailSettings.DebugEmailTemplates );
// I could also have a button on an admin page that executed this code to manually reset the cache in production.
TemplateManager.ResetCache();

似乎RazorEngine在TemplateService实例中存储编译模板的缓存。因此,您可以不时地重新创建TemplateService的新实例,以删除所有缓存的模板。

你也可以考虑使用我自己的库,它是基于RazorEngine的,并实现了自定义缓存机制和过期:http://www.nuget.org/packages/Essential.Templating.Razor