The Definitive C# Singleton(blueonionsoftware.com)

submitted by blueonionblueonion(150) 3 years, 8 months ago

The .NET framework makes it very easy to write thread safe, lazy initialized, singletons. Here's how.

5 comments |category: |Views: 819

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by dotnetchrisdotnetchris(157) 3 years, 7 months ago 0

Win for simplicity, I previously researched this and after many posts the final answer was exactly the same as yours here.

Isn't it fantastic when excellent code is written in 2 lines?

Reply

posted by evarlastevarlast(20) 3 years, 7 months ago 0

-1

DNK needs downmod

Reply

posted by cwbrandsmacwbrandsma(1711) 3 years, 7 months ago 0

Singletons are evil. Really. They cause more issues in software than any other single pattern.

Seriously, don't use them. If you really (think) you need one, make your IOC container do it for you instead.

Reply

posted by dotnetchrisdotnetchris(157) 3 years, 7 months ago 0

Singletons are so not evil at all when they are implemented in this pattern. It is 100% thread safe = zero fail. I can agree with you on the IoC container and I love IoC but many times it's an order above and beyond in complexity for a required solution unless it's built into the very core of the functionality many times simple singletons make perfect since for handling various needs. This way of declaring them is fool proof.

Reply

posted by cwbrandsmacwbrandsma(1711) 3 years, 7 months ago 0

Singletons are a nice easy pattern, that even if done correctly, can destroy code if used improperly.
The fundamental problem is when you try to unit test code that uses a singleton. One of the tenants of unit testing is code isolation.
Without spending some serious cash and buying TypeMock, you cannot isolate out a singleton (the correct word is Mock). This makes developing a test strategy VERY difficult.

Case in point, about bad singleton usage, NEVER-EVER implement your database layer (also called a repository) as a singleton. If you do, it will be impossible to isolate your database code from your business logic. This makes tests take longer to run, and you are having to test two sets of code. So if there is a failure, you can't be sure which set of code had a problem.

Reply

information Login or create an account to comment on this story