Is it better to rely on IOC Framework to implemented singleton? I heard that either double checked locking or relying on static constructor are not good practice, is this true?
4 Answers
In my opinion the lifetime of an object should be decided by the context creates it not enforced by the type of the object. In common sense not the ways to guarantee "singletonness" of an object are considered bad practice but the usage of the singleton pattern itself.
So, to answer your question: Yes, you should let the IoC container handle the lifetime of its objects.
Perhaps this answer may be helpful to you. It contains a basic pattern for a thread safe, lazy-loaded singleton.
It's pretty simply to implement the double checked locking pattern, and it's quite succinct and good practice. However, like @Andrew Barber said, improperly implementing it can be painful.
if(_instance == null)
{
lock(_myLockObject)
{
if(_instance == null)
_instance = new Something();
}
}
return _instance;
-
1I believe
_instance
should be declaredvolatile
for this to be correct. Commented May 6, 2011 at 14:55 -
I'm curious about this. The MSDN documentation says you should use volatile when not using a lock - msdn.microsoft.com/en-us/library/x13ttww7(v=vs.71).aspx– TejsCommented May 6, 2011 at 15:05
-
You're not within a lock when you perform the first check. Memory barriers etc get hideously complicated - there are concerns around the possibility of a reference being published before all the data within the object being published. This kind of thing is why I don't like it. Commented May 6, 2011 at 15:08
-
@Jon, I heard you have to declare not only _instance volatile, but all its properties volatile as well. Commented May 6, 2011 at 15:13
-
Object lifetime as the general rule should always be handled by an IOC container.
Manual object lifetime handling is prone to developer error, SRP violations, and extensive DRY violations.
volatile
makes it work, and that other memory barriers can make it work but that experts disagree about exactly what is required. I'm not going to try to give more information about what to do when experts disagree :) This is the reason I avoid DCL - it's easy to get wrong, and hard to reason about accurately. I likeLazy<T>
in .NET 4 which I trust to do the right thing :)Thread.MemoryBarrier
.