C# Generic Singleton

Occasionally I find myself writing a small .NET assembly that’s going to be used across a number of difference applications where I can’t assume that any particular Dependency Injection library fill be available.  In those situations, I often need to implement some sort of singleton object.  It’s on those occasions that I turn to the following generic singleton class I created based on Jon Skeet’s singleton implementations.

public static class Singleton
  where T : class, new()
{
  public static T Instance
  {
    get
    {
      return Nested.Instance;
    }
  }

  class Nested
  {
    internal static readonly T Instance = new T();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Nested()
    {
    }    
  }
}

The class is based on Jon’s fifth version of a singleton implementation.  With Jon’s approach, you have to copy the singleton code into your class that you want to make a singleton.  With my variation, you can copy the Singleton class into any C# project (or compile it into a reusable assembly) and then reuse it with any .NET class that has a default constructor.  You access the singleton instance of a class like this: Singleton.Instance

Here’s an example of using the Singleton class:

public class HelloWorldService
{
  public HelloWorldService
  {
    System.Console.WriteLine("New object!");
  }
  
  public void SayHello()
  {
    System.Console.WriteLine("Hello World!");
  }

  public void SayGoodbye()
  {
    System.Console.WriteLine("Goodbye World!");
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Singleton.Instance.SayHello();
    Singleton.Instance.SayGoodbye();
  }
}

When you run the example you get this console output:

New object!
Hello World!
Goodbye World!

Leave a Reply

Your email address will not be published. Required fields are marked *