Saturday, May 21, 2011

Singleton using Lazy<T>

Singleton is a common (and sometimes controversial) pattern. A few weekends ago, during the creation of a particularly hot chilli jam (recipe here, but quintuple the amount of chilli at least), I thought that perhaps the new .NET 4.0 class Lazy<T> would be a pleasing way of implementing a singleton.

Some judicious googling later - not a new idea at all. The only slightly unpleasant aspect to using Lazy<T> is that in 'naked' use, it expects a public default constructor - which of course is an excellent way to defeat a singleton implementation! But there are overloads that allow one to specify a Func<T> to create an instance, and even better, thread safety options can also be specified.

Another overload would therefore be useful - the ability to specify binding flags perhaps, to indicate to Lazy<T> that it should look for a private constructor. A little clumsy I suppose, since it would then be required to use reflection, but that is not so expensive a proposition these days.

MSDN documentation.

No comments: