DEV Community

Discussion on: Generic Singletons

 
thebuzzsaw profile image
Kelly Brown • Edited

I totally understand the desire to steer developers into the "pit of success". This is just an area I feel is more appropriate for something like a Roslyn Analyzer or at the very least code reviews. (And again, your blog post was good. I just had to be first to share the dissenting voice.)

The common issues you'll hear come around testability. Having to 'reset' the singleton is non-trivial at times, and it basically means tests cannot run in parallel. Plus, I don't know about you, but I've had times where I later realized I do need more than one instance. This is where I feel it's important to always use dependency injection so that you are insulated from such decisions. When a method can freely grab SomeSingleton<SomeWidget>.Instance, that dependency is less visible. You'd have to know to "Find All References" on the singleton itself.

I love the discourse. :)

Thread Thread
 
andreasjakof profile image
Andreas Jakof

I like discussing such things as well. If you look at my post „Brilliant but also horribly wrong“, I had like to learn from others, who know more than me.

And I usually don‘t use Singletons much. But in this case, I think, it is fine. The Singletons are usable in multiple threads and they mostly let me compare the membership of a user in an AAD-Group. And they NEVER change. If they would, they would no longer be of the same kind, not only the same instance.

And I know about the issues with testability as well... this is where I have a considerable lack of experience, even though I am already in the business for about 10 years now.

That’s why I am currently looking into DI in .Net Core. To make my code more testable. But then again, the code is mostly glue between systems and I am struggling with the basic approach, hie I will test it. Currently there are some basic unit tests, but lots of untested code, because the CD/CI server does not have access to all the credentials for the different systems I am glueing together. 😳