Created
August 6, 2014 20:24
-
-
Save abhilash0001/166b4da4a92b4b003ca7 to your computer and use it in GitHub Desktop.
Cache Helper - C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
namespace Custom.Helpers.Common | |
{ | |
public static class Cache | |
{ | |
private const string CacheSetting = "Cache.Duration"; | |
private static System.Web.Caching.Cache _cache { get { return System.Web.HttpContext.Current.Cache; } } | |
private static int _cacheDuration { get; set; } | |
static Cache() | |
{ | |
_cacheDuration = GetCacheDuration(); | |
} | |
public static void Set(string key, object value) | |
{ | |
_cache.Insert(key, value, | |
null, | |
System.Web.Caching.Cache.NoAbsoluteExpiration, | |
GetSlidingExpiration(_cacheDuration), | |
System.Web.Caching.CacheItemPriority.Default, | |
null); | |
} | |
public static T Get<T>(string key) | |
{ | |
T value = default(T); | |
if (Exists(key)) | |
value = (T)_cache.Get(key); | |
return value; | |
} | |
public static bool Exists(string key) | |
{ | |
return _cache.Get(key) != null; | |
} | |
private static TimeSpan GetSlidingExpiration(int duration) | |
{ | |
return new TimeSpan(0, duration, 0); | |
} | |
private static int GetCacheDuration() | |
{ | |
//default | |
int duration = 10; | |
var setting = ConfigurationManager.AppSettings[CacheSetting]; | |
if (!string.IsNullOrEmpty(setting)) | |
int.TryParse(setting, out duration); | |
return duration; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment