using Disco.Models.Repository; using Disco.Models.Services.Documents; using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Disco.Services.Expressions { public static class ExpressionCache { private static ConcurrentDictionary singleCache = new ConcurrentDictionary(); private static ConcurrentDictionary> cache = new ConcurrentDictionary>(); private static ConcurrentDictionary> fieldCache = new ConcurrentDictionary>(); private const string DocumentTemplateCacheTemplate = "DocumentTemplate_{0}"; public static Expression GetOrCreateSingleExpressions(string key, Func create) { if (singleCache.TryGetValue(key, out var result)) return result; else { result = create(); singleCache.TryAdd(key, result); return result; } } public static Dictionary GetOrCreateExpressions(string module, Func, List>> create) { if (cache.TryGetValue(module, out var result)) return result; else { return Create(module, create).Item1; } } public static List GetOrCreateFields(string module, Func, List>> create) { if (fieldCache.TryGetValue(module, out var result)) return result; else { return Create(module, create).Item2; } } public static void InvalidateCache(DocumentTemplate template) { InvalidateCache(string.Format(DocumentTemplateCacheTemplate, template.Id)); } public static void InvalidateCache(string module) { cache.TryRemove(module, out _); fieldCache.TryRemove(module, out _); } public static void InvalidateSingleCache(string key) { singleCache.TryRemove(key, out _); } public static Dictionary GetOrCreateExpressions(DocumentTemplate template, Func, List>> create) { return GetOrCreateExpressions(string.Format(DocumentTemplateCacheTemplate, template.Id), create); } public static List GetOrCreateFields(DocumentTemplate template, Func, List>> create) { return GetOrCreateFields(string.Format(DocumentTemplateCacheTemplate, template.Id), create); } private static Tuple, List> Create(string module, Func, List>> create) { var results = create(); cache.TryAdd(module, results.Item1); fieldCache.TryAdd(module, results.Item2); return results; } } }