After reading a bit about the System.Runtime.Caching in the .net 4 framework I've added a simple Cache class to my application.
Can I improve it or add additional useful functionality? Typing it out here I see that the cache checking is somewhat duplicated; could this be refactored?
Note: the two properties SuperUsers and TemplateLocation are just for an example of how the class would be used. Most properties would be a string or list.
/// <summary>
/// Cache class as singleton to make those often used
/// values that may change just that bit more speedy.
/// </summary>
/// <remarks>
/// Jon Skeets' singleton http://csharpindepth.com/Articles/General/Singleton.aspx
/// </remarks>
public sealed class Cacher
{
private readonly ObjectCache _cache = MemoryCache.Default;
public CacheItemPolicy Policy { get; set; }
private static readonly Cacher instance = new Cacher();
static Cacher()
{ }
private Cacher()
{
// expiration policy default
Policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10.0)
};
}
public static Cacher Instance
{
get { return instance; }
}
public string TemplateLocation
{
get
{
var loc = _cache["templatelocation"] as string;
if (string.IsNullOrEmpty(loc))
{
// hardcoded for test purposes
_cache.Set("templatelocation", getTemplateLocation(), Policy);
loc = _cache["templatelocation"] as string;
}
return loc;
}
}
public List<string> SuperUsers
{
get
{
var superUsers = _cache["superusers"] as List<string>;
if (superUsers == null)
{
// empty, so stick values in the cache
_cache.Set("superusers", GetSuperUsers(), Policy);
superUsers = _cache["superusers"] as List<string>;
}
return superUsers;
}
}
private string getTemplateLocation()
{
// hardcoded for test purposes
return @"C:\";
}
private List<string> GetSuperUsers()
{
// hardcoded for test purposes
return new List<string> {"John", "Anne", "Mark"};
}
public void Clear()
{
foreach (var cacheitem in _cache)
_cache.Remove(cacheitem.Key);
}
}
and using the class:
string location = Cacher.Instance.TemplateLocation;
List<string> sUsers = Cacher.Instance.SuperUsers;
GetSomething(...)
methods, or methods with even better names that do hint at side effects. – Leonid Apr 1 '12 at 3:25