C# – Factory for creating a singleton instance

cdependency-injectionfactory-methodnetsingleton

We have some legacy code that has a bunch of singletons all over the place (written in C#).

The singleton is a fairly "classic" implementation of the pattern:

public class SomeSingleton
{
    private static SomeSingleton instance;

    private SomeSingleton()
    {
    }

    public static SomeSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new SomeSingleton();
            }

            return instance;
        }
    } 
}

Note that thread safety is not a concern, so no locks are used.

In order to make the code more testable, and without making too many modifications, I'd like to modify this code to delegate the creation of the singleton instance in another class (a factory or similar pattern).

This can assist in creating a "test" instance for testing purposes, or the real version, as it is used now.

Is this a common practice? I could not find any reference to such pattern being used.

Best Answer

In the comments you say you are using Unity and Mono for game development. I am guessing that means Unity3D not Microsoft Unity. As such I would recommend that you ditch the singleton pattern that you are following and instead use dependency injection. I believe you can use Zenject with the unity3d framework.

The singleton class would be modified to be an instance of an interface like:

public class IImportantInterface
{
  DoSomethingImportant();
}

public class MySingletonImplementation: IImportantInterface
{
  public void DoSomethingImportant()
  {
    Console.WriteLine("This is Important!");
  }
}


public class DoImportantStuff
{
    private readonly IImportantInterface _ImportantInterface;

    public DoImportantStuff(IImportantInterface importantInterface )
    {
    _importantInterface = importantInterface;
    }


    public void DoSomething()
    {
    _importantInterface.DoSomethingImportant();
    }

}

Then in you startup logic you can register a singleton instance with Zenject:

Container.Bind<IImportantInterface>().ToSingle<MySingletonImplementation>(); 

A good blog post about this concept can be found here: http://www.unityninjas.com/code-architecture/dependency-injection/

Related Topic