Cramja
Cramja

Reputation: 65

Why isn't my COM class a Singleton?

For some reason, 2 objects are being created when they should be a Singleton.

I have a class Bridge whose purpose is to communicate from one application to another. The first app, App1, creates the bridge via COM and immediately calls the bridge's initialize method:

bool IBridge.Initialize(ref App1 theApp)
{
       if (theApp != null)
       {
            this.refToApp = theApp;
            log("Got bridge from App1");
            //spin up App2
            Process.Start([path to App2]);
       }
       else
       {
           log("theApp was null");
       }
       return true;
}

The Bridge class uses a singleton pattern but has a public default constructor so that COM will work properly with it but users of this class have to respect the fact that it's a singleton by only accessing it using the instance property.

[ComVisibleAttribute(true)]
[ProgId("[id that App1 uses to instantiate class]")]
public class Bridge : IBridge
{
    private static readonly _instance;

    public static COMBridge Instance
    {
        get
        {
            if(_instance == null){
                _instance = new Bridge();
            }
            return _instance
        }
    }

  public Bridge()
  {
       log("Called default constructor");
       if (_instance == null)
       {
            _instance = this;
       }
  }

 ...

However when App2 starts, it calls the getter for Instance and the constructor is called again. This is troublesome because the Bridge is a communication component and I need these two apps to talk to each other using the bridge.

Any tips?

Upvotes: 0

Views: 333

Answers (1)

user957902
user957902

Reputation: 3060

Assuming that the com object is configured to be an Out of Process com object (I am assuming this because it looks like it used to work that way from VB) then you have to jump through some hoops to get it to activate as an out of process object. by default .Net will load the object as an In Process com object, which means that every process will have its own copy of the object. Per the artical here

If you try using your COM object now, you might discover that it’s still loaded into the client’s process. The reason is that you have to tell COM you’re interested in out-of-process activation. If you’re using C/C++, pass CLSCTX_LOCAL_SERVER as the dwClsContext argument of the CoCreateInstance function. If you’re using C#/VB.NET, you’ll have to P/Invoke into CoCreateInstance for this.

Upvotes: 2

Related Questions