Is the following tread safe in a singleton pattern? I used the fourth singleton pattern in http://csharpindepth.com/Articles/General/Singleton.aspx
I'm concerned using an output parameter will break the whole principal.
public sealed class eCacheContent
{
private static readonly eCacheContent instance = new eCacheContent();
private ICacheManager _Cache = CacheFactory.GetCacheManager(ConfigurationManager.AppSettings["ContentCache"].ToString());
// for access method control locking
private static object syncRoot = new object();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static eCacheContent() { }
private eCacheContent() { }
public static eCacheContent Instance
{
get
{
return instance;
}
}
public bool TryGetValue(string key, out eContent output)
{
lock (syncRoot)
{
if (Contains(key))
{
ObjectCloner helper = new ObjectCloner();
eContent tmp = (eContent)this._Cache.GetData(key);
output = helper.Clone(tmp);
return true;
}
output = new eContent();
return false;
}
}
public void Add(string key, object value)
{
// Initiase the helper class for cloning
if (CheckKeyIfValid(key))
{
ObjectCloner helper = new ObjectCloner();
// Remove if already exist
this.Remove(key);
// Add carbon copy
_Cache.Add(key, helper.Clone(value));
}
}
public void Flush()
{
_Cache.Flush();
}
private bool Contains(string key)
{
if (CheckKeyIfValid(key))
return _Cache.Contains(key);
else
return false;
}
private void Remove(string key)
{
if (Contains(key))
{
_Cache.Remove(key);
}
}
private bool CheckKeyIfValid(string key)
{
if ((key != null) && (key.Trim().Length != 0))
return true;
return false;
}
}
I'm concerned using an output parameter will break the whole principal.
In what way do you think an out parameter breaks the principle of a Singleton? By definition a singleton class "restricts the Instantiation of a class to one object" - your Instance property ensures that.
Your TryGetValue method is a helper method for pulling out cached versions of eContent, this is completely separate from your eCacheContent class.
Related
I am looking for a way to cast object variable into type with generic type argument specified by other variable of type Type.
I am limited to .NET 3.5, so no dynamic can be used :(
Main idea here is that I have access to a dictionary:
Dictionary<Type, object> data;
Data to that dictionary is added only in form of:
data.Add(T, new DataSub<T>(someValueOfTypeT));
The problem is, that when I'm trying to reverse the process:
foreach(var dataType in data.Keys) {
var dataValue = data[dataType];
ProcessDataValue(dataType, dataValue);
}
Now the question is how do I manage to cast object to DataSub?
Simplified DataSub.cs:
public class DataSub<T>
{
private T _cache;
public T Value {
get { return _cache; }
set { _cache = value; }
}
}
How it could work in ProcessDataValue:
public void ProcessDataValue(Type dataType, object dataValue)
{
var data = dataValue as DataSub<dataType>;
if (data == null) return;
AddProcessedDataValue(dataType, data.Value.ToString());
}
if you can do minimal changes to the classes you posted and if - as is showed in your example - what you would do with DataSub.Value is invoking ToString, may be you can obtain the result you need with
public interface IDataSub {
bool MatchesType(Type t);
object GetValue();
}
public class DataSub<T> : IDataSub {
private T _cache;
public T Value {
get { return _cache; }
set { _cache = value; }
}
public bool MatchesType(Type t) {
return typeof(T) == t; // or something similar, in order to handle inheritance
}
public object GetValue() {
return Value;
}
}
public class Client {
Dictionary<Type, IDataSub> data = new Dictionary<Type, IDataSub>() ;
public void AddData<T>(T someValueOfTypeT) {
data.Add(typeof(T), new DataSub<T> { Value = someValueOfTypeT });
}
public void UseData() {
foreach(var dataType in data.Keys) {
var dataValue = data[dataType];
ProcessDataValue(dataType, dataValue);
}
}
public void ProcessDataValue(Type dataType, IDataSub dataValue)
{
if(dataValue.MatchesType(dataType))
AddProcessedDataValue(dataType, dataValue.GetValue().ToString());
}
}
If the usage of DataSub.Value.ToString is only an example, and in the real world you need to access DataSub.Value using its type T, you should apply a broader reworking of you code.
What do you think about the following approach? This is an application of the pattern I like call set of responsibility (I wrote the linked post about this topic), a variation of GoF's chain of responsibility:
public interface IDataSub {
object GetValue();
}
public class DataSub<T> : IDataSub {
private T _cache;
public T Value {
get { return _cache; }
set { _cache = value; }
}
public object GetValue() {
return Value;
}
}
public interface IDataHandler {
bool CanHandle(Type type);
void Handle(object data);
}
public class Client {
private readonly Dictionary<Type, IDataSub> data = new Dictionary<Type, IDataSub>();
private readonly IList<IDataHandler> handlers = new List<IDataHandler>();
public void AddData<T>(T someValueOfTypeT) {
data.Add(typeof(T), new DataSub<T> { Value = someValueOfTypeT });
}
public void RegisterHandler(IDataHandler handler) {
handlers.Add(handler);
}
public void UseData() {
foreach(var dataType in data.Keys) {
handlers.FirstOrDefault(h => h.CanHandle(dataType))?.Handle(data[dataType].GetValue());
}
}
// Lambda-free version
// public void UseData() {
// foreach(var dataType in data.Keys) {
// for (int i = 0; i < handlers.Count; i++) {
// if (handlers[i].CanHandle(dataType)) {
// handlers[i].Handle(data[dataType].GetValue());
// break; // I don't like breaks very much...
// }
// }
// }
// }
}
class StringDataHandler : IDataHandler {
public bool CanHandle(Type type) {
// Your logic to check if this handler implements logic applyable to instances of type
return typeof(string) == type;
}
public void Handle(object data) {
string value = (string) data;
// Do something with string
}
}
class IntDataHandler : IDataHandler {
public bool CanHandle(Type type) {
// Your logic to check if this handler implements logic applyable to instances of type
return typeof(int) == type;
}
public void Handle(object data) {
int value = (int) data;
// Do something with int
}
}
This approach allow you to decouple data storage and data iteration logic from data-handling logic specific of different data-types: IDataHandler's implementations known what type of data they can handle and cast generic object reference to desired type. If you prefer, you can merge CanHandle method into Handle method, remving the former method and changing UseData to
public void UseData() {
foreach(var dataType in data.Keys) {
foreach(var handler in handlers) {
handler.Handle(dataType, data[dataType].GetValue())
}
}
}
and handler implementations to
class IntDataHandler : IDataHandler {
public void Handle(Type dataType, object data) {
if(typeof(int) == type) {
int value = (int) data;
// Do something with int
}
}
}
This variant is slightly more type-safe, because in the first variant was already possibile to call Handle method without a previus call to CanHandle.
If you liked this approach, you can bring it forward, simplifying your data structure and converting data from IDictionary to IList:
public interface IDataSub {
object GetValue();
}
public class DataSub<T> : IDataSub {
private T _cache;
public T Value {
get { return _cache; }
set { _cache = value; }
}
public object GetValue() {
return Value;
}
}
public interface IDataHandler {
bool CanHandle(object data);
void Handle(object data);
}
public class Client {
private readonly IList<IDataSub> data = new List<IDataSub>();
private readonly IList<IDataHandler> handlers = new List<IDataHandler>();
public void AddData<T>(T someValueOfTypeT) {
data.Add(new DataSub<T> { Value = someValueOfTypeT });
}
public void RegisterHandler(IDataHandler handler) {
handlers.Add(handler);
}
public void UseData() {
foreach(var dataItem in data) {
var value = dataItem.GetValue();
handlers.FirstOrDefault(h => h.CanHandle(value))?.Handle(value);
}
}
// Lambda-free version as above...
class StringDataHandler : IDataHandler {
public bool CanHandle(object data) {
// Your logic to check if this handler implements logic applyable to instances of String
return data is string;
}
public void Handle(object data) {
string value = (string) data;
// Do something with string
}
}
class IntDataHandler : IDataHandler {
public bool CanHandle(Type type) {
// Your logic to check if this handler implements logic applyable to instances of int
return type is int;
}
public void Handle(object data) {
int value = (int) data;
// Do something with int
}
}
The CanHandle-free variant can simplify IDataHandler interface and its implementation in this case, too...
I hope my answer can help you resolving you design scenario; I build it upon an approach I like very much, because it allows to apply subtype-specific logic to instances of different classe, given they share a common superclass (as object in my code samples).
I am trying to implement a thread safe dictionary singleton class for caching purpose.
namespace SingletomDict
{
public sealed class MySingleton:IDisposable
{
private static readonly Lazy<MySingleton> coll = new Lazy<MySingleton>(() => new MySingleton());
private static Dictionary<string, object> mycoll;
public static MySingleton Instance
{
get
{
return coll.Value;
}
}
private MySingleton()
{
mycoll = new Dictionary<string, object>();
}
private void SetProperty<T>(string name, T value)
{
mycoll.Add(name, value);
}
private object GetProperty(string name)
{
object value = mycoll[name];
return value;
}
public dynamic this[string index]
{
get { return GetProperty(index); }
set { SetProperty(index, value); }
}
public void ReSet()
{
mycoll = new Dictionary<string, object>();
}
}
In the main method, I will be invoking the object as
MySingleton.Instance["LS"] = "AAA";
MySingleton.Instance["AB"] = "BBB";
MySingleton.Instance.ReSet();
I did some research to find the correct implementation. But I couldn't find the appropriate example. Thanks
First declare an interface that describes how you want to use this. Perhaps ICache with a get and set method. (I'd steer clear of dynamic.)
public interface ICache
{
T Get<T>(string key);
void Set(string key, object value);
}
Then write an implementation. Your implementation doesn't need to specify what the internals are.
public class Cache : ICache
{
private readonly ConcurrentDictionary<string, object> _cache
= new ConcurrentDictionary<string, object>();
public T Get<T>(string key)
{
object cached;
if(_cache.TryGetValue(key, out cached) && cached is T)
{
return(T) cached;
}
return default(T);
}
public void Set(string key, object value)
{
_cache.AddOrUpdate(key, value, (s, o) => value);
}
}
If you want to make this a singleton, you can make the constructor private and create a static singleton instance. I would lean toward not doing that. It's better for other classes to depend on the ICache interface than on the implementation, and an interface doesn't have static methods.
Depending on the interface means that you can substitute it with different implementations, like one that depends on MemoryCache.
public class InMemoryCache : ICache
{
private readonly MemoryCache _cache = MemoryCache.Default;
public T Get<T>(string key)
{
var cached = _cache[key];
return cached is T ? (T) cached : default(T);
}
public void Set(string key, object value)
{
_cache[key] = value;
}
}
If you use a dependency injection (IoC) container you can tell it which implementation of ICache to use for a class that needs an instance of it, and you can specify that the same instance should be provided each time. That way you get to use a single instance of your class as if it was a singleton without having to code it as a singleton.
I've just created some kind of generic repository, it seems to be working, my only problem is, is there any solution to avoid to use public constructor in classes what has to be instantiated to the repository?
My code is here:
public sealed class repository
{
private static readonly object _lock = new object();
private static readonly object _syncroot = new object();
private static volatile repository _instance;
private static readonly Dictionary<int, object> _dict
= new Dictionary<int, object>();
private repository()
{
}
public static repository instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null) _instance = new repository();
}
}
return _instance;
}
}
public void allocate<Tc>(int id, object constructor_param) where Tc : Irepository<Tc>, new()
{
lock (_syncroot)
{
if (!_dict.ContainsKey(id))
{
var n = new Tc();
_dict.Add(id, n.New(constructor_param));
}
}
}
public T get<T>(int id)
{
lock (_syncroot)
{
return (T) _dict[id];
}
}
}
public interface Irepository<out T>
{
T New(object constructor_param);
}
public class RpSupportedClass : Irepository<RpSupportedClass>
{
public object _constructor_param;
private RpSupportedClass(object constructor_param)
{
_constructor_param = constructor_param;
}
public RpSupportedClass()
{
}
public RpSupportedClass New(object constructor_param)
{
return new RpSupportedClass(constructor_param);
}
}
So the problem is that I have to create a default public constructor:
public RpSupportedClass()
{
}
...because of type parameter. I need type parameter by this way because I would like to use parameter in class instantiate sometimes.
Is there any way out?
Thank you!
Here is an example of a property I have, coded as simply as possible
private IEnumerable<int> _blocks;
private bool _blocksEvaluated;
public IEnumerable<int> Blocks
{
get
{
if (!_blocksEvaluated)
{
_blocksEvaluated = true;
_blocks = this.CalculateBlocks(0).FirstOrDefault();
}
return _blocks;
}
}
This is verbose; I would like to make it more concise if possible. The following would be acceptable...
private Lazy<IEnumerable<int>> _blocks =
new Lazy<IEnumerable<int>>(() => this.CalculateBlocks(0).FirstOrDefault());
... but it doesn't compile.
Keyword 'this' is not valid in a static property, static method, or static field initializer
So I came up with the following
struct MyLazy<TResult>
{
private bool evaluated;
private TResult result;
public TResult Evaluate(Func<TResult> func)
{
if (!evaluated)
{
evaluated = true;
result = func();
}
return result;
}
}
private MyLazy<IEnumerable<int>> _blocks;
public IEnumerable<int> Blocks
{
get { return _blocks.Evaluate(() => this.CalculateBlocks(0).FirstOrDefault()); }
}
Which I like best, but is there a better way?
Note - I realize that mutable structs are usually evil, but they seem really useful for this one particular problem.
Just initialize your field in the constructor.
public class MyClass
{
public MyClass()
{
_blocks = new Lazy<IEnumerable<int>>(() => this.CalculateBlocks(0).FirstOrDefault());
}
private readonly Lazy<IEnumerable<int>> _blocks;
}
You can't use this when initializing an instance field, but you can simply initialize it in the constructor to address that.
private Lazy<IEnumerable<int>> _blocks;
public MyClass()
{
_blocks = new Lazy<IEnumerable<int>>(
() => this.CalculateBlocks(0).FirstOrDefault());
}
public IEnumerable<int> Blocks
{
get
{
return _blocks.Value;
}
}
I have a generic base class for value caching functionality.
public abstract class CachedValueProviderBase<T> : ICachedValueProvider<T> where T : class
{
private Cache Cache { set; get; }
protected string CacheKey { get; set; }
protected int CacheSpanInMinutes { get; set; }
private static readonly object _cacheLock = new object();
public T Values
{
get
{
T value = Cache[CacheKey] as T;
if (value == null)
{
lock (_cacheLock)
{
value = Cache[CacheKey] as T;
if (value == null)
{
value = InitializeCache();
}
}
}
return value;
}
}
protected CachedValueProviderBase()
{
Cache = HttpRuntime.Cache;
CacheSpanInMinutes = 15;
}
public T CacheValue(T value)
{
if (value != null)
{
lock (_cacheLock)
{
Cache.Insert(CacheKey, value, null, DateTime.UtcNow.AddMinutes(CacheSpanInMinutes),
Cache.NoSlidingExpiration);
}
}
return value;
}
private T InitializeCache()
{
T value = Initialize();
CacheValue(value);
return value;
}
protected abstract T Initialize();
}
I have several classes that make use of this base class and as long as the T is different it is fine. When two sub classes use the same T, string for example, they share the same cache lock object. What is the best way of implementing the logic in a base class but still giving each sub class it's own cache lock object?
Update
After the suggestions below I have updated my class:
public abstract class CachedValueProviderBase<T> : ICachedValueProvider<T> where T : class
{
private Cache Cache { set; get; }
protected string CacheKey { get; set; }
protected int CacheSpanInMinutes { get; set; }
private object _cacheLock = new object();
public T Values
{
get
{
T value = Cache[CacheKey] as T;
if (value == null)
{
lock (_cacheLock)
{
value = Cache[CacheKey] as T;
if (value == null)
{
value = InitializeCache();
}
}
}
return value;
}
}
protected CachedValueProviderBase()
{
Cache = HttpRuntime.Cache;
CacheSpanInMinutes = 15;
}
public T CacheValue(T value)
{
if (value != null)
{
Cache.Insert(CacheKey, value, null, DateTime.UtcNow.AddMinutes(CacheSpanInMinutes),
Cache.NoSlidingExpiration);
}
return value;
}
private T InitializeCache()
{
T value = Initialize();
CacheValue(value);
return value;
}
protected abstract T Initialize();
}
}
My sub classes are now singletons so I could get rid of the static cachelock object making it an instance variable.
I had to take a good look at your code, to find out if it was correct. Once I noticed your cache is a HttpRuntime.Cache, it made sense. The HttpRuntime.Cache is thread-safe. Otherwise you would have had several thread-safety problems. With your current, code I advice you to do the following:
private string CacheKey { get; set; }
protected CachedValueProviderBase(string cacheKey)
{
this.CacheKey = cacheKey + "_" + typeof(T).FullName;
}
By supplying the cacheKey as constructor argument and making the property private (or readonly would do), you prevent it from being changed by later on. By appending the type name to the key, you prevent cache conflicts since everybody is using the same cache.
One last note. The lock in the CacheValue method is redundant, since the Cache is thread-safe.
Well, just remove the static modifier on your cacheLock object.
That keyword forces the field to be shared between all instances of subclasses that share the same generic parameter type.
If you remove it, the cacheLock object will be private to each instance of a subclass, regardless of the generic parameter's type.
private static readonly object _cacheLock = new object();
Should be :
private readonly object _cacheLock = new object();
Hope that helps
I handled this by implementing an abstract method in my base class GetCacheLockObject().
protected abstract object GetCacheLockObject();
Each derived class then returns its own reference to the cache lock object:
private static readonly object _cacheLockObject = new Object();
protected override object GetCacheLockObject()
{
return _cacheLockObject;
}
Calls to lock in the shared base class caching code then reference this method rather than an object in the base class.