views:

4306

answers:

16

I have the following C# singleton pattern, is there any way of improving it?

    public class Singleton<T> where T : class, new()
    {

        private static object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }

        public Singleton()
        { }

    }

Preferred usage example:

class Foo : Singleton<Foo> 
{
}

Related:

An obvious singleton implementation for .NET?

+9  A: 

Courtesy of Judith Bishop, http://patterns.cs.up.ac.za/

This singleton pattern implementation ensures lazy initialisation.

//  Singleton PatternJudith Bishop Nov 2007
//  Generic version

public class Singleton<T> where T : class, new()
{
    Singleton() { }

    class SingletonCreator
    {
        static SingletonCreator() { }
        // Private object instantiated with private constructor
        internal static readonly T instance = new T();
    }

    public static T UniqueInstance
    {
        get { return SingletonCreator.instance; }
    }
}
Darksider
Im sorry, im no longer comfortable with this being correct, the problem is that you end up having a type that is both newable and can be accessed via the singleton ...
Sam Saffron
Just a quick question Sam: How did you manage to create a new instance of the class? According to the code above, the constructor is private...
Darksider
This pattern is good, but there's one thing that bothers me : the new() type constraint implies that the singleton has a public constructor, which breaks the singleton pattern. I think this constraints should be removed, and Activator.CreateInstance should be used to call the protected constructor
Thomas Levesque
T must have a _public_ `new()`
Alexey Romanov
@Darksider, Singleton<Dog> ... var d = new Dog() works just fine... which I would prefer did not. See: cade's answer.
Sam Saffron
+1  A: 
public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();

   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}

There's no ambiguity in .NET around initialization order; but this raises threading issues.

blowdart
This is really not an improvement, for one its not using generics so you have to cast Instance when you subclass, its also potentially initializing the object before you really need it.
Sam Saffron
Actually it's not initializing before you need it; read the MSDN link provided; "the instance is created the first time any member of the class is referenced".
blowdart
+10  A: 

According to Jon Skeet in Implementing the Singleton Pattern in C# the code you posted is actually considered as bad code, because it appears broken when checked against the ECMA CLI standard.

Also watch out: everytime you instantiate your object with a new type of T, it becomes another instance; it doesn't get reflected in your original singleton.

Jon Limjap
That a good post ... I amended the question to reflect these changes
Sam Saffron
A: 

I quite liked your original answer - the only thing missing (according to the link posted by blowdart) is to make the _instance variable volatile, to make sure it has actually been set in the lock. I actually use blowdarts solution when I have to use a singleton, but I dont have any need to late-instantiate etc.

Wyzfen
Yerp adding volatile is a good point
Sam Saffron
isn't volatile a c++ thing?
RWendi
See: http://msdn.microsoft.com/en-us/library/x13ttww7(VS.71).aspx
Sam Saffron
A: 

You don't need all that, C# already has a good singleton pattern built-in.

static class Foo

If you need anything more interesting than that, chances are your new singleton is going to be just different enough that your generic pattern is going to be useless.

EDIT: By "anything more interesting" I'm including inheritance. If you can inherit from a singleton, it isn't a singleton any more.

Jonathan Allen
Wrong. There are quite a few situations where singletons are useful and static classes do not work eg. try making this static.public TimeSpan this[string filename] { get { return new TimeSpan(); } set { } }
Sam Saffron
Also, you can't inherit static methods so you can't use inheritance to build your singleton class.
wizlb
I'll amend my comment... a static class is a GOOD solution for grouping static methods, but technically, it does not implement singleton since there is no "instance" and you don't get instance semantics like inheritance.
wizlb
The singleton could implement an interface or extend another class. That will work in static a static class with static methods.
Fedearne
+4  A: 

This code won't compile, you need "class" constraint on T.

Also, this code requires public constructor on target class, which is not good for singleton, because you can't control at compile time that you obtain (single) instance only via Instance property (or field). If you don't have any other static members except Instance, you are ok to go with just this:

class Foo
{
  public static readonly Instance = new Foo();
  private Foo() {}
  static Foo() {}
}

It is thread safe (guaranteed by CLR) and lazy (instance is created with first access to type). For more discussion about BeforeFieldInit and why we need static constructor here, see http://www.yoda.arachsys.com/csharp/beforefieldinit.html.

If you want to have other public static members on type, but create object only on access to Instance, you may create nested type, like in http://www.yoda.arachsys.com/csharp/singleton.html

Ilya Ryzhenkov
You have the correct answer. This is the best implementation because it is the simplest, it's built into the language and you're not burning your base class to implement a trivial feature.
wizlb
+2  A: 

I don't think that you really want to "burn your base class" so that you can save 2 lines of code. You don't really need a base class to implement singleton.

Whenever you need a singleton, just do this:

class MyConcreteClass
{
  #region Singleton Implementation

    public static readonly Instance = new MyConcreteClass();

    private MyConcreteClass(){}

  #endregion

    /// ...
}
wizlb
+3  A: 

More details on this answer on a different thread : http://stackoverflow.com/questions/246710/how-to-implement-a-singleton-in-c

Binoj Antony
+1  A: 

I was looking for a better Singleton pattern and liked this one. So ported it to VB.NET, can be useful for others:

Public MustInherit Class Singleton(Of T As {Class, New})
    Public Sub New()
    End Sub

    Private Class SingletonCreator
        Shared Sub New()
        End Sub
        Friend Shared ReadOnly Instance As New T
    End Class

    Public Shared ReadOnly Property Instance() As T
        Get
            Return SingletonCreator.Instance
        End Get
    End Property
End Class
dr. evil
A: 

My contribution for ensuring on demand creation of instance data:


/// <summary>Abstract base class for thread-safe singleton objects</summary>
/// <typeparam name="T">Instance type</typeparam>
public abstract class SingletonOnDemand<T> {
    private static object __SYNC = new object();
    private static volatile bool _IsInstanceCreated = false;
    private static T _Instance = default(T);

/// <summary>Instance data</summary> public static T Instance { get { if (!_IsInstanceCreated) lock (__SYNC) if (!_IsInstanceCreated) _Instance = Activator.CreateInstance<T>(); return _Instance; } } }
A: 

pff... again... :)
My contribution for ensuring on demand creation of instance data:


/// <summary>Abstract base class for thread-safe singleton objects</summary>
/// <typeparam name="T">Instance type</typeparam>
public abstract class SingletonOnDemand<T> {
  private static object __SYNC = new object();
  private static volatile bool _IsInstanceCreated = false;
  private static T _Instance = default(T);

  /// <summary>Instance data</summary>
  public static T Instance {
    get {
      if (!_IsInstanceCreated)
        lock (__SYNC)
          if (!_IsInstanceCreated) {
            _Instance = Activator.CreateInstance<T>();
            _IsInstanceCreated = true;
          }
          return _Instance;
    }
  }
}
If you replace '= default(T)' with '= new T()' then you don't have to do the double-check locking and just 'get { return _Instance; }'
SnOrfus
A: 

As requested, cross posting from my original answer to another question.

My version uses Reflection, works with non-public constructors in the derived class, is threadsafe (obviously) with lazy instantiation (according to the article I found linked below):

public class SingletonBase<T> where T : class
{
    static SingletonBase()
    {
    }

    public static readonly T Instance = 
        typeof(T).InvokeMember(typeof(T).Name, 
                                BindingFlags.CreateInstance | 
                                BindingFlags.Instance |
                                BindingFlags.Public |
                                BindingFlags.NonPublic, 
                                null, null, null) as T;
}

I picked this up a few years ago, not sure how much is mine, but googling on the code might find the original source of the technique if it wasn't me.

This is the oldest source of the code that I can find that was not me posting it.

Cade Roux
+1  A: 

:/ the generic "singleton" pattern of judith bishop seems kinda flawed, its always possible to create several instances of type T as the constructor must be public to use it in this "pattern". In my opinion it has absolutely nothing to do with singleton, its just a kind of factory, which always returns the same object, but doesn't make it singleton... as long as there can be more than 1 instance of a class it can't be a singleton. Any reason this pattern is top-rated?

public sealed class Singleton
{
  private static readonly Singleton _instance = new Singleton();

  private Singleton()
  {
  }

  public static Singleton Instance
  {
    get
    {
      return _instance;
    }
  }
}

static initializers are considered Thread-Safe.. i don't know but you shouldn't use idioms of singleton at all, if you wrap my code above its not more than 3 lines... and inheriting from a singleton doesn't make any sense either

haze4real
A: 
public static class LazyGlobal<T> where T : new()
{
    public static T Instance
    {
        get { return TType.Instance; }
    }

    private static class TType
    {
        public static readonly T Instance = new T();
    }
}

// user code:
{
    LazyGlobal<Foo>.Instance.Bar();
}

Or:

public delegate T Func<T>();

public static class CustomGlobalActivator<T>
{
    public static Func<T> CreateInstance { get; set; }
}

public static class LazyGlobal<T>
{
    public static T Instance
    {
        get { return TType.Instance; }
    }

    private static class TType
    {
        public static readonly T Instance = CustomGlobalActivator<T>.CreateInstance();
    }
}

{
    // setup code:
    // CustomGlobalActivator<Foo>.CreateInstance = () => new Foo(instanceOf_SL_or_IoC.DoSomeMagicReturning<FooDependencies>());
    CustomGlobalActivator<Foo>.CreateInstance = () => instanceOf_SL_or_IoC.PleaseResolve<Foo>();
    // ...
    // user code:
    LazyGlobal<Foo>.Instance.Bar();
}
uvw
A: 

Saw one a while ago which uses reflection to access a private (or public) default constructor:

public static class Singleton<T>
{
    private static object lockVar = new object();
    private static bool made;
    private static T _singleton = default(T);

    /// <summary>
    /// Get The Singleton
    /// </summary>
    public static T Get
    {
        get
        {
            if (!made)
            {
                lock (lockVar)
                {
                    if (!made)
                    {
                        ConstructorInfo cInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
                        if (cInfo != null)
                            _singleton = (T)cInfo.Invoke(new object[0]);
                        else
                            throw new ArgumentException("Type Does Not Have A Default Constructor.");
                        made = true;
                    }
                }
            }

            return _singleton;
        }
    }
}
JDunkerley
A: 

Try this generic Singleton class implementing the Singleton design pattern in a thread safe and lazy way (thx to wcell).

public abstract class Singleton<T> where T : class
{
 /// <summary>
 /// Returns the singleton instance.
 /// </summary>
 public static T Instance
 {
  get
  {
   return SingletonAllocator.instance;
  }
 }

 internal static class SingletonAllocator
 {
  internal static T instance;

  static SingletonAllocator()
  {
   CreateInstance(typeof(T));
  }

  public static T CreateInstance(Type type)
  {
   ConstructorInfo[] ctorsPublic = type.GetConstructors(
    BindingFlags.Instance | BindingFlags.Public);

   if (ctorsPublic.Length > 0)
    throw new Exception(
     type.FullName + " has one or more public constructors so the property cannot be enforced.");

   ConstructorInfo ctorNonPublic = type.GetConstructor(
    BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], new ParameterModifier[0]);

   if (ctorNonPublic == null)
   {
    throw new Exception(
     type.FullName + " doesn't have a private/protected constructor so the property cannot be enforced.");
   }

   try
   {
    return instance = (T)ctorNonPublic.Invoke(new object[0]);
   }
   catch (Exception e)
   {
    throw new Exception(
     "The Singleton couldnt be constructed, check if " + type.FullName + " has a default constructor", e);
   }
  }
 }
}
w0land