Join Nostr
2026-10-26 15:37:57 UTC

codementor on Nostr: Learn: Singleton One instance for the whole app, with a global access point. ...

Learn: Singleton

One instance for the whole app, with a global access point.

```csharp
Console.WriteLine(ReferenceEquals(Config.Instance, Config.Instance));

sealed class Config
{
private static readonly Lazy<Config> instance = new(() => new Config());
public static Config Instance => instance.Value;
private Config() { }
}
```

It prints True: both reads return the same object. Lazy<T> creates it once, on first use, even with many threads; the object itself must still be thread-safe.
In ASP.NET Core, prefer AddSingleton in DI: same effect, easier to test. Watch out: singletons are shared global state.

Read more: https://www.geeksforgeeks.org/system-design/singleton-design-pattern/

#tip · TIP-051