Singleton in .NET

Marco Dorantes
2 min readJun 26, 2021
Singleton

If I need a process-level global write-once/read-many state, a global variable, a Singleton, in .NET Runtime, then I keep in mind what I said at the post: Know your design tools — The Singleton case.

It is also relevant to keep in mind:

  1. the Visual C# language specification about Static constructors,
  2. the section on Static Constructors of the Visual C# Programming Guide,
  3. the description of what BeforeFieldInit does, and
  4. the category (Performance) and the ‘When to suppress warnings’ section of the CA1810 Rule.

The observations on that old post have been useful for me over the years. Specially while designing stateful software services, where the use of locking, global state, global variables, or Singletons do not hinder throughput. On the other hand, in the context of stateless software services processing a high number of concurrent requests, whose scalability is very important, then –to be clear–, I do not prefer any explicit use of locking, any global state, any global variables or any Singleton.

Here is a demonstrative version of a .NET/Visual C#-based Singleton derived from the sample code of such old post and a couple of MSTest test cases as evidence of its correctness, included post-conditions for same class instance and for same global value: Singleton in .NET.

--

--

Marco Dorantes

Reflective software craftsman and systems thinking enthusiast.