What is a Singleton Pattern?
Singleton Pattern is one of the software design patterns which uses only one instantiation of a class.
When do we use a Singleton Pattern?
Example - Error Logger
Difference between Static Class and Singleton Pattern
| Static Class | Singleton Pattern |
| Cannot be instantiated. | Only one instance throughout the cycle. |
| Can contain only static members & static methods. | Can contain both static and non-static variables and methods. |
| Cannot have a simple public constructor. | Can have a simple public constructor. |
Implementation
Add a static implementation of the same class datatype as one of the fields/properties.
- public class Singleton
- {
- private static Singleton instance;
- private Singleton() { }
- public static Singleton Instance
- {
- get
- {
- if (instance == null)
- instance = new Singleton();
- return instance;
- }
- }
- //instance methods
- }
Exception Logger
When you want to log the exception, you don’t need to instantiate every time you want to log. A single object can be used to log the exceptions. Below is a sample implementation of Exception Logging Service.
Code Snippet
- using System;
- public class ExceptionLoggingService
- {
- private static ExceptionLoggingService _instance = null;
- public static ExceptionLoggingService Instance
- {
- get
- {
- if (Instance == null)
- {
- _instance = new ExceptionLoggingService();
- }
- return _instance;
- }
- }
- public void LogError(Exception ex)
- {
- try
- {
- }
- catch (Exception exx)
- {
- }
- }
- }

Karel KrálPosted Nov 13, 2018, 8:51 AM
Your example is not thread safe. You can create multiple instances of singleton easily.
Dinesh GabhanePosted Nov 11, 2018, 3:08 AM
Thanks for sharing. can you please share code to use this error logging from controller r from any class? It will be really helpful.
Rushi MehtaPosted Oct 30, 2018, 11:25 PM
Nic Article.Thanks for sharing