Specify apartment state to use when instantiating out of proc COM object
Asked Answered
C

1

6

I created a COM object in .NET and registered it as a COM+ server application with Pooling = 1 using regsvcs. I am currently hunting down a bug and therefore need to make sure that this COM object is running in STA, not MTA. How can I specify this?
Any of the following will help me:

  • A setting in the Component services snap in
  • A setting / code fragment which makes the COM object to only allow STA and not Both
  • A setting / code fragment in C# on the caller side that tells COM+ that the COM object should be initialized with STA

Update:
I tried to manually change the ThreadingModel entry in the registry from Both to Apartment. This didn't help either, because when I try to instantiate the COM object, I get an COMException (0x80110802) and the event viewer says:

The threading model of the component specified in the registry is inconsistent with the registration database. The faulty component is: <MyComponent>

Is there any other place I need to change the threading model? For example in that "registration database"? Where can I find it?

Thanks!

Colb answered 20/4, 2011 at 7:0 Comment(0)
C
5

OK, I inserted the following code in the class that is exposed as COM object and it seems to work:

[ComRegisterFunction]
private static void Register(Type registerType)
{
    if (registerType != null)
    {
        using (RegistryKey clsidKey = Registry.ClassesRoot.OpenSubKey("CLSID"))
        {
            using (RegistryKey guidKey = clsidKey.OpenSubKey(registerType.GUID.ToString("B"), true))
            {
                using (RegistryKey inproc = guidKey.OpenSubKey("InprocServer32", true))
                {
                    inproc.SetValue("ThreadingModel", "Apartment", RegistryValueKind.String);
                }
            }
        }
    }
}

I don't understand at all, why changing the ThreadingModel by hand didn't yield the same result, but I don't care...

Colb answered 20/4, 2011 at 8:48 Comment(1)
Not good enough, only works if the coclass was registered before. Consider RegistrationServices.RegisterTypeForComClients() to get the basic keys into place first.Watterson

© 2022 - 2024 — McMap. All rights reserved.