开发者

Singleton implementation question

Is it b开发者_高级运维etter 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?


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜