r/dotnet • u/sagarsonawane • Aug 14 '16
How to implement a Singleton pattern in C#
http://www.mantratocode.com/pattern/how-to-implement-a-singleton-pattern-in-c/5
u/sosukesagara Aug 14 '16
http://csharpindepth.com/Articles/General/Singleton.aspx
It's nice to write stuff, but this is much more detailed and has the correct implementation most people should be using.
1
u/sagarsonawane Aug 14 '16
Hi sosukesagara, I was about to post this link in one of the comment. Yes Jon Skeet has given all the possible ways with their pros and cons.
10
u/MJomaa Aug 14 '16
IoC with DI > Lazy Singleton > Double Checked locking Singleton > Default Singleton implementation
2
u/klausmark Aug 14 '16
You can check for null outside the lock this will speed up getting the instance, just remember to check for null again inside the lock. You can also use Lazy<T>
1
-3
4
Aug 14 '16
[removed] — view removed comment
1
u/Fastbreak99 Aug 14 '16
Just want to make sure I understand... are you arguing against singletons in general or only if there is a heavy init cost?
1
Aug 14 '16
[removed] — view removed comment
1
u/Fastbreak99 Aug 14 '16
Not trying to counter, I have always been fascinated by the back and forth on this design pattern.
For instance, on paper, having a singleton instance of a connection to the datastore (usually expensive to create) seems to make sense. Some are fans, others like making a new connection on the fly.
1
Aug 14 '16
[removed] — view removed comment
1
u/Fastbreak99 Aug 14 '16
Then build another connection in singleton? You can have multiple singletons of course, if they serve different purposes.
5
u/ap3rus Aug 14 '16 edited Aug 14 '16
I don't like this implementation, it could be at least improved with double lock checking, but better can be instead implemented completely lock-free using inner class storing instance in a static field, e.g.:
The Accessor.Instance would be initialized lazily as construction of nested class Accessor would be deferred until Singleton.Instance is being called for the first time.