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
Published at
2026-10-26 15:37:57 UTCEvent JSON
{
"id": "342f596a05c6322e8b9d833b2618314baa13a93a0a5dcd26cb56e9a7d2549936",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1793029077,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Singleton\n\nOne instance for the whole app, with a global access point.\n\n```csharp\nConsole.WriteLine(ReferenceEquals(Config.Instance, Config.Instance));\n\nsealed class Config\n{\n private static readonly Lazy\u003cConfig\u003e instance = new(() =\u003e new Config());\n public static Config Instance =\u003e instance.Value;\n private Config() { }\n}\n```\n\nIt prints True: both reads return the same object. Lazy\u003cT\u003e creates it once, on first use, even with many threads; the object itself must still be thread-safe.\nIn ASP.NET Core, prefer AddSingleton in DI: same effect, easier to test. Watch out: singletons are shared global state.\n\nRead more: https://www.geeksforgeeks.org/system-design/singleton-design-pattern/\n\n#tip · TIP-051",
"sig": "3fc1e74e75d73ce4d2635392d5d2588ade11c64028b6fd6d49821a1cbbfca9a1b6ba92db9e87a0cae80e0e7963e3abc4b308d3bc1db26ebd663857ed8658de81"
}