What is Singleton Pattern?
The Singleton Pattern is a creational design pattern that ensures only one instance of a class exists throughout the application and provides a global access point to it.
Why Use Singleton?
- Share a single instance across the app
- Avoid multiple object creation
- Manage global resources efficiently
Real-Time Scenario
- Logging service
- Configuration settings
- Cache service
- Application-wide settings
Basic Implementation (Classic)
public class Logger
{
private static Logger _instance;
private Logger() { }
public static Logger GetInstance()
{
if (_instance == null)
_instance = new Logger();
return _instance;
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
Usage
var logger1 = Logger.GetInstance();
var logger2 = Logger.GetInstance();
Console.WriteLine(logger1 == logger2); // True
logger1.Log("Hello Singleton");
👉 Both variables point to the same instance
Thread-Safe Singleton (Recommended)
public class Logger
{
private static readonly Lazy<Logger> _instance =
new Lazy<Logger>(() => new Logger());
private Logger() { }
public static Logger Instance => _instance.Value;
public void Log(string message)
{
Console.WriteLine(message);
}
}
.NET Core Way (Best Practice)
👉 Don’t manually create singleton
👉 Use Dependency Injection
builder.Services.AddSingleton<ILogService, LogService>();
public class LogService : ILogService
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
👉 Same instance shared across entire app automatically
Key Concept
Instead of:
var obj1 = new Logger();
var obj2 = new Logger();
We do:
var obj1 = Logger.Instance;
var obj2 = Logger.Instance;
👉 Only one object exists
Advantages
- Ensures single instance
- Saves memory/resources
- Global access point
- Useful for shared services
Disadvantages
- Hard to unit test (global state)
- Can create hidden dependencies
- Not suitable for all scenarios
- Tight coupling if overused
When to Use
- When exactly one instance is required
- When managing shared resources
- When object creation is expensive
- When global access is needed
Real Project Mapping (.NET + Angular)
| Feature | Usage |
|---|---|
| Logging service | Singleton |
| Configuration service | Singleton |
| Cache manager | Singleton |
| Auth/session service | Singleton |
Pro Tip (Advanced .NET Usage)
- Always prefer DI-based Singleton in ASP.NET Core
- Avoid static singletons unless necessary
- Combine with Options pattern for configuration
Summary
Singleton Pattern helps you:
- Maintain a single shared instance
- Manage global resources efficiently
- Improve performance and consistency
👉 Perfect for logging, caching, configuration services
Comments
Post a Comment