lundi 7 septembre 2020

Cache class - Need design suggestion

We're building a simple cache to be used across our web application.

The first instinct is use a static variable to hold the cache.

public class SimpleCacheProvider : ICacheProvider
{
    //This is .NET's in-memory Cache
    private static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions()); 

    public void Add<T>(string key, T value)
    {
        _cache.Set(key, value);
    }

    public bool Contains(string key)
    {
        return _cache.Get(key) != null;
    }

    public void Remove(string key)
    {
        _cache.Remove(key);
    }

    public bool TryGetValue<T>(string key, out T value)
    {
        return _cache.TryGetValue(key, out value);
    }
}
  1. Would you prefer to hold the cache as a static variable or would you choose to have a singleton instance for the class. Is there any advantage of choosing one over the other?
  2. How does IDisposable work in static vs singleton scenario? Would there be any advantage w.r.t garbage collection while choosing one over the other?

Any guidance welcome.

Aucun commentaire:

Enregistrer un commentaire