user3398315
user3398315

Reputation: 331

How do I ensure only one instance of the object of the class is created?

In my class A, I have a ZMQ object

    public void StartLogging(object connection)
    {
        var ctxt = new ZMQ.Context();
        var publisher = ctxt.Socket(ZMQ.SocketType.PUB);
        publisher.Bind("tcp://127.0.0.1:5000");
        if (connection is uint)
        {
            Console.WriteLine("strange");
            Console.ReadLine();
        }
    }

Class B will do something like

ClassA test=new ClassA();

Class C will also do something the same

ClassA test=new ClassA();

This will result in 2 ZMQ object being created binding to the same port which will result in error. How do I fix this problem?

Upvotes: 3

Views: 3233

Answers (3)

Usman Waheed
Usman Waheed

Reputation: 553

Welcome to

singleton pattern

here is what MSDN has: http://msdn.microsoft.com/en-us/library/ff650316.aspx

Upvotes: 0

crthompson
crthompson

Reputation: 15865

A singleton is what you need. Jon Skeet's excellent article will tell you more than you need to know.

In your case it might look something like this:

public void StartLogging(object connection)
{
    var ctxt = Singleton.Instance.Context();
    var publisher = ctxt.Socket(ZMQ.SocketType.PUB);
    publisher.Bind("tcp://127.0.0.1:5000");
    if (connection is uint)
    {
        Console.WriteLine("strange");
        Console.ReadLine();
    }
}

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

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

    private Singleton()
    {
    }

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

Upvotes: 6

bit
bit

Reputation: 4487

A singleton pattern would help you.

This works even for multi threaded application.

Upvotes: 1

Related Questions