coreframework/Core-Framework — Issue #7: Wrong Singleton design pattern implementation
Author: karpenkov
Created: 2011-12-30 07:03:37+00:00
State: open

Hi,

The current Singleton design pattern implementation seems to be not correct as it will perform locking every time you're trying to access instance. It should use double-check algorithm or standard .Net 4.0 **System.Lazy** type which guarantees thread-safe lazy-construction.

Current implementation sample:

```csharp
private static LoginHolderWidgetViewerVerb instance;

private static readonly Object syncRoot = new Object();

public static LoginHolderWidgetViewerVerb Instance
{
get
{
lock (syncRoot)
{
return instance ?? (instance = new LoginHolderWidgetViewerVerb());
}
}
}
```

It would be better to use something like this (http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx)

```csharp
private static Lazy instance = new Lazy(() => new LoginHolderWidgetViewerVerb());

public static LoginHolderWidgetViewerVerbInstance
{
get { return instance.Value; }
}
```

Also please make sure to use private constructor in order to prevent users from creating their instances of the class.