patterncsharpMinor
Global data singleton
Viewed 0 times
singletonglobaldata
Problem
I need a global data in my application. My application uses several threads to access and add items to my global variable. The global variable is a
ConcurrentDictionary I choose to ensure data is added to the variable. What do you think about my approach?public class GlobalData
{
private static volatile GlobalData instance;
private volatile ConcurrentDictionary _data = new ConcurrentDictionary();
private static object syncRoot = new Object();
public static GlobalData Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new GlobalData();
}
}
return instance;
}
}
public void Add(string id, object obj)
{
_data.TryAdd(id, obj);
}
public object Get(string id)
{
object value;
_data.TryGetValue(id, out value);
return value;
}
}Solution
- Singletons are evil
- Even if you do want to use it, use
Lazyinstead of manually doing double-checked locking
Best solution would be to leverage IoC container to inject dependencies you need.
Context
StackExchange Code Review Q#26472, answer score: 7
Revisions (0)
No revisions yet.