EnVisageOnline/Main/Source/EnVisage/Code/Cache/Cache.cs

76 lines
2.2 KiB
C#

using Autofac;
using Autofac.Extras.NLog;
using Autofac.Integration.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
namespace EnVisage.Code.Cache
{
public abstract class Cache<T>
{
#region private fields
private AutofacDependencyResolver resolver => DependencyResolver.Current as AutofacDependencyResolver;
private ILogger _logger;
#endregion
#region properties
protected virtual string CACHE_KEY {get; private set;}
public IEnumerable<T> Value
{
get
{
if (!CacheManager.Instance.IsInCache(CACHE_KEY))
SetValuesToCache();
return (IEnumerable<T>)CacheManager.Instance.GetCacheData(CACHE_KEY);
}
}
protected ILogger Logger => _logger ?? (_logger = resolver?.ApplicationContainer?.Resolve<ILogger>());
#endregion
public Cache()
{
//Logger.Debug($"Constructor of type {this.GetType().ToString()}() has been called");
if (!CacheManager.Instance.IsInCache(CACHE_KEY))
SetValuesToCache();
}
public Cache(bool populate)
{
//Logger.Debug($"Constructor of type {this.GetType().ToString()}(bool populate) has been called. populate = {populate}");
if (!CacheManager.Instance.IsInCache(CACHE_KEY) && populate)
SetValuesToCache();
}
public void Invalidate()
{
if (CacheManager.Instance.IsInCache(CACHE_KEY))
CacheManager.Instance.RemoveFromCache(CACHE_KEY);
}
public bool ContainsEntry()
{
return CacheManager.Instance.IsInCache(CACHE_KEY);
}
public virtual void AddValueToCache(T obj)
{
CacheManager.Instance.AddToCache(CACHE_KEY, obj);
}
public virtual T GetValueFromCache()
{
return (T) CacheManager.Instance.GetCacheData(CACHE_KEY);
}
protected virtual void SetValuesToCache()
{
using (EnVisageEntities context = new EnVisageEntities())
{
var value = context.ProjectAccesses.AsNoTracking().ToList();
CacheManager.Instance.AddToCache(CACHE_KEY, value);
}
}
}
}