/SharpTAL/TemplateCache/MemoryTemplateCache.cs
C# | 81 lines | 36 code | 10 blank | 35 comment | 1 complexity | a564b3f4e7bcb822320d9ba131cf42c3 MD5 | raw file
Possible License(s): Apache-2.0
- //
- // MemoryTemplateCache.cs
- //
- // Author:
- // Roman Lacko (backup.rlacko@gmail.com)
- //
- // Copyright (c) 2010 - 2013 Roman Lacko
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
- namespace SharpTAL.TemplateCache
- {
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- using SharpTAL.TemplateProgram;
- public class MemoryTemplateCache : AbstractTemplateCache
- {
- Dictionary<string, TemplateInfo> templateInfoCache;
- object templateInfoCacheLock;
- /// <summary>
- /// Initialize the template cache
- /// </summary>
- public MemoryTemplateCache() :
- base()
- {
- templateInfoCache = new Dictionary<string, TemplateInfo>();
- templateInfoCacheLock = new object();
- }
- public override TemplateInfo CompileTemplate(string templateBody, Dictionary<string, Type> globalsTypes, List<Assembly> referencedAssemblies)
- {
- lock (templateInfoCacheLock)
- {
- // Generate template program
- TemplateInfo ti = GenerateTemplateProgram(templateBody, globalsTypes, referencedAssemblies);
- // Generated template found in cache
- if (templateInfoCache.ContainsKey(ti.TemplateKey))
- {
- return templateInfoCache[ti.TemplateKey];
- }
- // Generate code
- ICodeGenerator codeGenerator = new CodeGenerator();
- ti.GeneratedSourceCode = codeGenerator.GenerateCode(ti);
- // Generate assembly
- AssemblyGenerator assemblyCompiler = new AssemblyGenerator();
- Assembly assembly = assemblyCompiler.GenerateAssembly(ti, true, null, null);
- // Try to load the Render() method from assembly
- ti.RenderMethod = GetTemplateRenderMethod(assembly, ti);
- templateInfoCache.Add(ti.TemplateKey, ti);
- return ti;
- }
- }
- }
- }