나는이 RazorEngine 3.4.1.0 작업있어 늦게 월 2014
키를 누른 다음 실행 싼 Razor.Run(name, model)
를 호출 캐시에 템플릿을 넣어 비싼 Razor.Compile(content, name)
를 호출하는 것입니다을 설치 한 템플릿.
템플릿 내용을 읽는 것은 비용이 많이 들지만 디스크에서 읽는 것과 관련하여 비용이 많이들 수 있습니다. 따라서 내 솔루션은 템플릿 내용을 한 번만 가져옵니다. 이것은 캐싱이 너무 많을 수 있으므로 조심하십시오!
여기 TemplateBase<T>
서브 클래스 내에서 사용하는 RenderPartial
방법입니다. 동일한 템플릿에 대한 여러 호출에 대해 매우 빠르게 실행됩니다.
public abstract class SqlTemplate<T>: TemplateBase<T>
{
public string RenderPartial(string templateName, object model = null)
{
// loading a template might be expensive, so be careful to cache content
if (Razor.Resolve(templateName) == null)
{
// we've never seen this template before, so compile it and stick it in cache.
var templateContent = GetTemplateContent(templateName);
Razor.Compile(templateContent, templateName);
}
// by now, we know we've got a the template cached and ready to run; this is fast
var renderedContent = Razor.Run(templateName, model);
return renderedContent;
}
private string GetTemplateContent(string templateName)
{
... your implementation here
}
}
는 또한 RazorEngineConfigurator.Configure()
를 호출하여이 같이 할 수있는이 기본 클래스 (SqlTempalte<T>)
를 사용하는 면도기를 말할 필요가;
public static class RazorEngineConfigurator
{
private static bool configured = false;
public static void Configure()
{
if (configured)
{
return;
}
var templateConfig = new TemplateServiceConfiguration
{
BaseTemplateType = typeof(SqlTemplate<>),
EncodedStringFactory = new RazorEngine.Text.RawStringFactory()
};
RazorEngine.Razor.SetTemplateService(new TemplateService(templateConfig));
configured = true;
}
}
이 this SO answer 없이는 불가능했을 거예요 - 이유도 그 중 하나에게까지 - 투표를 포기하지? :)
편집 - 좀 더 세분화 된 방식으로 캐싱을 수행해야하는 경우 RazorEngineTemplateService
및 ITemplateResolver
을 사용하여 다른 방법을 사용해야합니다.
다음은 초보자 용 코드입니다.
public static RazorEngineTemplateService CreateService(ITemplateResolver resolver, ICollection<string> namespaces)
{
Check.IsNotNull(resolver, "resolver");
var config = new TemplateServiceConfiguration();
config.BaseTemplateType = typeof(PlainTextTemplate<>);
config.EncodedStringFactory = new RazorEngine.Text.RawStringFactory();
config.Resolver = resolver;
config.Namespaces = new HashSet<string>(namespaces);
var service = new RazorEngineTemplateService(config);
return service;
}
ITemplateResolver
는 예를 들어, 구현할 수 있도록, 템플릿 내용에 템플릿 이름을 회전 디스크에서 캐시 된 콘텐츠를로드하는 CachedFileTemplateResolver
.
내 질문에 답변 해 주셔서 감사합니다. 왜 내가 이것을 보지 못했는지 나는 모른다. 그래서 내가 면도기에 이름을 건네 주면됩니다. 가늘고 형체는 이전에 내가 면도칼이라고 불렀던 것과 동일합니다. 같은 이름으로 가깝습니다. 그런 다음 새 어셈블리를 만드는 대신 캐시 된 어셈블리를 사용하게됩니까? – Rabbi
@Rabbi 예, 이것이 작동하는 방식입니다. 템플리트 이름을 전달할 때 템플릿 내용의 해시 코드를 가져 와서 동적으로 컴파일 된 유형과 함께 메모리 캐시에 저장합니다. 다음 번에 호출 할 때 템플릿 문자열의 해시 코드가 변경되지 않은 경우 템플릿 유형을 자유롭게 인스턴스화하고 실행할 수 있습니다. 그렇지 않은 경우 캐시의 기존 유형을 무효화하고 새 템플리트 내용에 대한 기본을 다시 컴파일합니다. –
참고로, 현재 RazorEngine에서 작동하는 방식이 아닙니다. Profilling이 Razor.Parse가 웹 호출마다 2 초 지연을 일으키는 것으로 나타났습니다. Razor.GetTemplate(); Razor.Run(); 정확하게 우리를 위해 캐싱을 시작했습니다. – KallDrexx