using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Persistence.Caching { /// /// The InMemory registry looks up objects in an in-memory dictionary for fast retrival /// internal class InMemoryCacheProvider : IRepositoryCacheProvider { #region Singleton private static readonly Lazy lazy = new Lazy(() => new InMemoryCacheProvider()); public static InMemoryCacheProvider Current { get { return lazy.Value; } } private InMemoryCacheProvider() { } #endregion private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); /// /// Retrives an object of the specified type by its Id /// /// The type of the object to retrive, which implements /// The Guid Id of the Object to retrive /// public IEntity GetById(Type type, Guid id) { var compositeKey = GetCompositeId(type, id); var containsKey = _cache.ContainsKey(compositeKey); if (containsKey) { return _cache[compositeKey]; } return null; } /// /// Retrives objects of the specified type by their Ids /// /// The type of the objects to retrive, which implements /// The Guid Ids of the Objects to retrive /// public IEnumerable GetByIds(Type type, List ids) { var list = (from id in ids select GetCompositeId(type, id) into key let containsKey = _cache.ContainsKey(key) where containsKey select _cache[key]).ToList(); return list; } /// /// Retrives all objects of the specified type /// /// The type of the objects to retrive, which implements /// public IEnumerable GetAllByType(Type type) { var list = _cache.Keys.Where(key => key.Contains(type.Name)).Select(key => _cache[key]).ToList(); return list; } /// /// Saves an object in the registry cache /// /// /// public void Save(Type type, IEntity entity) { _cache.AddOrUpdate(GetCompositeId(type, entity.Id), entity, (x, y) => entity); } /// /// Deletes an object from the registry cache /// /// /// public void Delete(Type type, IEntity entity) { IEntity entity1; bool result = _cache.TryRemove(GetCompositeId(type, entity.Id), out entity1); } public void Clear() { _cache.Clear(); } private string GetCompositeId(Type type, Guid id) { return string.Format("{0}-{1}", type.Name, id.ToString()); } private string GetCompositeId(Type type, int id) { return string.Format("{0}-{1}", type.Name, id.ToGuid()); } } }