Introduction
After a long while, I had to create a singleton service while I'm developing a feature for the ABP Framework. Then I decided to write an article about that: Why and how we should use the singleton pattern over a static class?
OK, I agree that creating singleton class or static class, doesn't matter, is not a good practice. However, in practical, it can be unavoidable in some points. So, which one we should prefer? While the article title already answers this question, I will explain details of this decision in this article.
While this article uses C# as the programming language, the principles can be applied in any object oriented language.
You can get the source code from my GitHub samples repository.
Using Dependency Injection?
Then you are lucky and you are doing a good thing, you can use the singleton lifetime.
ASP.NET Core allows you to register a class with the singleton lifetime. Assuming that you've a MyCache class and you want to register it with the singleton lifetime. Write this inside the ConfigureServices method of your Startup class and that's all:
services.AddSingleton<MyCache>();
You still need to care about multi-threading, you shouldn't inject transient/scoped services into your singleton service (see my dependency injection best practices guide for more), but you don't need to manually implement the singleton pattern. ASP.NET Core Dependency Injection system handles it. Whenever you need to the MyCache service, just inject it like any other service.
However, there can be some reasons to manually implement the singleton pattern
jhardin 5 years ago
I'm missing something... How can the SingletonCache test create the SingletonCache object for _singletonCache if the SingletonCache() default constructor is "protected internal" and the test class does not derive from SingletonCache? The test shouldn't be able to instantiate the class because the default constructor is hidden. Thanks for enlightenment!
yaswanthram@yahoo.in 5 years ago
He mentioned in the article about internalsvisibleto concept. It answers your question.