我最近升级到 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();