Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations
Wrong constructor called in COM+: sneaky, sneaky bug

Here's another nasty one that tried to bite me today. Let's say I have the following classes:

public class COMPlusClass : ServicedComponent
{
   public COMPlusClass()
   {
      // Default initialization.
   }

   public COMPlusClass (string data)
   {
      // Parameterized initialization.
   }
}

public class Client
{
    public Client()
    {
       COMPlusClass cpc = new COMPlusClass("I am a client");
    }
}

Which constructor do you think will be called?

Naturally, I wouldn't ask if it was the second one. Much to my surprise, the first constructor was called when I instantiated the COM+ component.

Why is this? Because COM+, due to its COM heritage, requires all components to expose a default, public, parameterless constructor and always initializes through it.

Why didn't I get an error, then? Because I'm writing .NET classes that don't know in advance that they will be instantiated through COM+. If all I know of COMPlusClass came from a COM type library, the second ctor probably wouldb't be exposed. But since I see it as a .NET class, I can believe I am instantiating the parametrized constructor. COM+ probably discards my precious string along the way.

Solution? Add some sort of Initialize method to pass the construction data.

Published Thursday, August 30, 2007 5:35 PM by Avner Kashtan

Filed under: , ,

Comments

# re: Wrong constructor called in COM+: sneaky, sneaky bug@ Thursday, August 30, 2007 2:28 PM

That one caught me a couple of years ago. When you think about it, it does makes sense. Unfortunately, it lets you get away with it until you go to deploy, then it is too late!

Eric Wild

Leave a Comment

(required) 
(required) 
(optional)
(required)