It has been a while since I needed to develop a singleton in .NET, and now that I am working in .NET 4 I thought it was a good time to revisit the implementation and take advantage of new language features.
So without much fanfare, here it is:
Public NotInheritable Class MySingleton Private Shared _instance As Lazy(Of MySingleton) = New Lazy(Of MySingleton)(Function() New MySingleton()) ''' <summary> ''' Hide the constructor ''' </summary> ''' <remarks></remarks> Private Sub New() ' nothing to do End Sub ''' <summary> ''' Singleton instance ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Shared ReadOnly Property Instance As MySingleton Get Return _instance.Value End Get End Property End Class
The .NET 4
Lazy class by default ensures that the singleton is thread-safe.
If you use the
Lazy class and do not pass in any parameters, it will construct the type automatically for you... which means that the class must have a public constructor method with no parameters. By passing a value factory delegate into the constructor of the
Lazy class, we can keep our constructor private and thereby force others to use our Instance property and truly make a Singleton.