Skip navigation.

Managed Extensions Framework (MEF) Looks InterestingAll recent postsjQuery(Sulky)

Microsoft PAG Still Doesn't Understand Singleton

When I was starting out in .NET a while ago, I used to read architectural “guidance” put out by Microsoft’s very own Patterns & Practices group. Back then, the guidance was sound enough because we were all in the same boat. However, as years went by, the proverbial “community” took the lead on architectural innovation, and P&P has been playing lame catch ever since.

Here’s one thing I clearly remember from old P&P documentation: they never understood the Singleton pattern. Really, there’s nothing extremely complicated about Singleton, but the big gotcha is thread safety!

Via the mighty ScottGu cometh think link: ASP.NET Patterns Developers Should Know by Alex Homer from the Patterns and Practices (PAG) team at Microsoft. Take a look at the implementation of the Singleton pattern. As my good friend Don the Plumber XML points out, IT’S NOT THREAD SAFE.

Amazing that PAG still doesn’t get it. Wait, no, they kind of do if you look at this code on the PAG site. Or at least they get double-locking, but don’t list two other important implementations. Can you, guys, talk to each other before you write something as embarrassing?

Normally, I would quietly refactor into a proper singleton and put a comment upon check-in, but when this snake oil is presented for sound guidance I have issues with that.

Comments

Comment permalink 1 James Crowley |
We've since updated the article with a clarification from Alex on the implementation of singleton pattern, along with a link off to Jon Skeet's article on the various implementations.

The note added by Alex is as follows:

"Note that this implementation does not perform locking while it creates the instance. In reality, in this specific scenario, if a second thread should create a second instance it will not affect operation because the content is read-only and is the same for all instances. If you absolutely need to confirm that only one instance can ever exist, you should apply locks while checking for
and creating the instance. For more details, see Implementing the Singleton Pattern in C# (http://www.developerfusion.com/article/9407/) and
Data & Object Factory Singleton Pattern (http://www.dofactory.com/Patterns/PatternSingleton.aspx)"

Emails and Notifications

Would you like to be notified when somebody responds to this post?  Would you like to have these comments emailed to you?

Submit your comment

Please enter only text since all HTML tags except hyperlinks will be stripped. Hyperlinks will become live links. Any comments with flaming or offensive language will be deleted. Be courteous to other posters. Thank you.

Your name (required):
Your email (optional):
Your site's URL (optional):
Enter this number
Type in the number above:
Comment (required):