Reputation: 11480
Create the singleton class based on 6th version provided in Jon Skeet's book check here.
Class - CacheSingleton
public sealed class CacheSingleton<TK,TV>
{
private static readonly Lazy<ICache<TK,TV>> lazyIgnite =
new Lazy<ICache<TK,TV>>(() =>
{
NearCacheConfiguration nearCacheConfig = new NearCacheConfiguration { NearStartSize = 10240000 };
var nearCache = IgniteInstance.GetOrCreateNearCache<TK, TV>(SingletonCacheName,nearCacheConfig);
return nearCache;
});
/// <summary>
///
/// </summary>
private static string SingletonCacheName = string.Empty;
/// <summary>
///
/// </summary>
public static ICache<TK, TV> Instance(string cacheName)
{
SingletonCacheName = cacheName;
return lazyIgnite.Value;
}
/// <summary>
///
/// </summary>
private CacheSingleton() { }
}
Modification to the original Article:
Instance
is a Method instead of property, since I need to supply the CacheName, for fetching the correct CacheIssues:
Tk,TV
types, since at no place I am able to factor in string
input except the first time, second time on-wards it will always fetch same instance even if string value if different.Lazy
type takes Func<T>
, there's no scope of an additional parameter.Any pointer to factor in the string input, along with TK,TV
Upvotes: 1
Views: 299
Reputation: 3221
What about using a ConcurrentDictionary
?
public static class CacheSingleton<TK, TV>
{
private static readonly ConcurrentDictionary<string, ICache<TK, TV>> lazyIgnite = new ConcurrentDictionary<string, ICache<TK, TV>>();
public static ICache<TK, TV> GetInstance(string cacheName)
{
return lazyIgnite.GetOrAdd(cacheName, name =>
{
NearCacheConfiguration nearCacheConfig = new NearCacheConfiguration { NearStartSize = 10240000 };
var nearCache = IgniteInstance.GetOrCreateNearCache<TK, TV>(name, nearCacheConfig);
return nearCache;
});
}
}
This is a lazy and thread-safe cache for your instances.
Perhaps you also want to implement a Clear
method to reset the cache.
Upvotes: 3
Reputation: 109567
Couldn't you use a ConcurrentDictionary
to implement this? Something like:
public static class CacheSingleton<TK, TV>
{
public static ICache<TK, TV> Instance(string cacheName)
{
return _cache.GetOrAdd(cacheName, create);
}
static ICache<TK, TV> create(string cacheName)
{
// Code to create an ICache<TK, TV> given cacheName.
return null; // Stubbed.
}
static readonly ConcurrentDictionary<string, ICache<TK, TV>> _cache = new ConcurrentDictionary<string, ICache<TK, TV>>();
}
Upvotes: 2