Singleton Design Pattern implementation in C#

Singleton design pattern is one of the GoF (Gang of Four) design patterns, falls under Creational pattern. It ensures at any given point of time only one instance of an object is alive and it does supports lazy initialization.
Why and what is the use of Singleton pattern?
- To preserve global state of a type.
- To share common data across application.
- To reduce overhead of instantiating a heavy object again and again.
- Suitable for Facades and Service proxies.
- To cache objects in-memory and reuse them throughout the application.
Example scenarios where Singleton can be used
- Service Proxies: In an application invoking a service aka API is an extensive operation. And creating a Service client itself time consuming process. By having a Service proxy as a Singleton this overhead can be reduced.
- Facades: Like service proxy, Database connections are another one example where Singleton can be used to produce better performance and synchronization.
- Logs: I/O is a heavier operation, by having a single instance of a Logger, required information can be written to same file as logs.
- Data sharing: Configuration values and any constant values can be kept in Singleton to read by other components of the application.
- Caching: Data fetching is a time taking process whereas caching required data in the application memory avoids DB calls and Singleton can be used here to handle the caching with thread synchronization in an efficient manner comparing to static type.
Implementation of Singleton pattern
At any point of time the application should hold only one instance of the Singleton type. So in order to achieve it, we should mark the constructor of the type as private member and an method or a property should be exposed to outer world to give the Singleton instance.
The above C# implementation of Singleton pattern also provides lazy initialization. So whenever the first invoke made to the Instance property the actual Singleton instance is initialized. Unless required the Singleton will not have an instance in memory.
✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.