Alex Rivera | Logout

C# Singleton with constructor that accepts parameters

Asked 2009-07-14T00:36:46.403
23

I want to create a static class or singleton class that accepts a reference to another object in its constructor. Static classes are out, but I figured I could create a singleton that accepts parameters in its constructor. So far I haven't had any luck figuring out or googling the syntax. Is this possible? if so, how do I do it?

Sorry for no example in the initial post, I wrote it in a rush. I have the feeling that my answer is already in the replies, but here's some clarification of what I want to do:

I want to create a single instance of a specific type (said Singleton), but that single instance of the type needs to hold a reference to a different object.

For example, I might want to create a Singleton "Status" class, which owns a StringBuilder object and a Draw() method that can be called to write said StringBuilder to the screen. The Draw() method needs to know about my GraphcisDevice in order to draw. So what I want to do it this:

public class Status
{
private static Status _instance;
private StringBuilder _messages;
private GraphicsDevice _gDevice;

private Status(string message, GraphicsDevice device)
{
    _messages.Append(message);
    _gDevice = device;
}

// The following isn't thread-safe

// This constructor part is what I'm trying to figure out
public static Status Instance // (GraphicsDevice device) 
    {
    get
        {
        if (_instance == null)
            {
            _instance = new Status("Test Message!", device); 
            }
        return _instance;
        }
    }

public void UpdateMessage
...

public void Draw()
    {
    // Draw my status to the screen, using _gDevice and _messages
    }
}  

All over the code, I retrieve my Status Singleton and call its UpdateMessage() method.

private Status _status = Status.Instance; // + pass reference to GraphicsDevice
_status.UpdateMessage("Foo!");

Then, in my main class I also retrieve the singl

Edit
Report

1 Answer

2

What you are describing is a Generic Singleton. It looks like this:

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

    public static T Instance
    {
        get { return SingletonCreator.instance; }
    }

    class SingletonCreator
    {
        static SingletonCreator() { }

        internal static readonly T instance = new T();
    }
}

http://www.codeproject.com/KB/cs/genericsingleton.aspx

answered 2009-07-14T00:41:11.507

Your Answer