SingletonFactory.CreateInstance has a threading bug:
if (_instances.ContainsKey(key))
return _instances[key];
lock (_lock)
{
T result = _createInstance(request);
if (result != null)
{
_instances[key] = result;
}
}
The read check is done outside the lock so it is possible multiple threads could not find the singleton, then try to create it, leading to more than 1 singleton instance getting created. Either the read needs to be done inside the lock or a second copy of it needs to be pasted into the lock (for lazy locking). If it were up to me I'd do the latter. :)
if (_instances.ContainsKey(key))
return _instances[key];
lock (_lock)
{
if (_instances.ContainsKey(key))
return _instances[key];
T result = _createInstance(request);
if (result != null)
{
_instances[key] = result;
}
}
SingletonFactory.CreateInstance has a threading bug:
The read check is done outside the lock so it is possible multiple threads could not find the singleton, then try to create it, leading to more than 1 singleton instance getting created. Either the read needs to be done inside the lock or a second copy of it needs to be pasted into the lock (for lazy locking). If it were up to me I'd do the latter. :)