Caching and SRP pt2
In the comments of the previous example Petar suggested a refactroring to reduce the coupling between object using the cache and the cache it's self, he proposed using generics and it works just fine in the IOC, let's take a look. Starting with the interface
1: public interface ICache<T>
2: { 3: void Add(T res, string key);
4: T Get(string key);
5: void Remove(string key);
6: }
now the cache class
1: public class Velocity<T> : ICache<T>
2: { 3: private const string CACHE = "MyCache";
4:
5: public void Add(T res, string key)
6: { 7: var CacheCluster1 = new CacheFactory();
8: var Cache1 = CacheCluster1.GetCache(CACHE);
9: Cache1.Add(key, res);
10: }
11:
12: public T Get(string key)
13: { 14: var CacheCluster1 = new CacheFactory();
15: var Cache1 = CacheCluster1.GetCache(CACHE);
16:
17: return (T) Cache1.Get(key);
18: }
19:
20: public void Remove(string key)
21: { 22: var CacheCluster1 = new CacheFactory();
23: var Cache1 = CacheCluster1.GetCache(CACHE);
24:
25: Cache1.Remove(key);
26: }
27: }
The object using the cache now looks like the following.
1: public class BasketActions
2: { 3: private ICache<Basket> _cache;
4:
5: public BasketActions(ICache<Basket> cache)
6: { 7: _cache = cache;
8: }
9:
10: public Basket Get(int basketid)
11: { 12: var cacheValue = cache.Get(basketid);
13: if(cacheValue == null)
14: { 15: var res = GetBasket(basketid);
16: if(res != null)
17: { 18: cache.Add(res, cachekey);
19: }
20: return res;
21: }
22: return cacheValue;
23: }
24:
25: private Basket GetBasket(int basketid)
26: { 27: ...
28: }
29: }
and finally we change our IOC call to the following.
1: IOC.Register<ICache<Basket>, Velocity<Basket>>();