C# Singletons

C# Singletons


Dependency Injection (.NET Core):

builder.Services.AddSingleton<ILoggerService, LoggerService>();


Lazy<T>  (.NET 4+):

public sealed class Logger

{

    // 1. Lazy<T> ensures thread-safe, deferred initialization

    private static readonly Lazy<Logger> _instance = new Lazy<Logger>(() => new Logger());

    // 2. Public global access point

    public static Logger Instance => _instance.Value;

    // 3. Private constructor prevents external instantiation

    private Logger() { // Initialization logic here }

    public void Log(string message) { Console.WriteLine($"[LOG]: {message}"); }

}

Logger.Instance.Log("Application started.");


Old Ways:

1) not thread safe

2) lock

3) x2 lock

4) not quite as lazy, but thread-safe without using locks

5) fully lazy instantiation 


Comments

Popular posts from this blog

Whitelabel Options

Free AI Tools

Await