Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

com

com+

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!

like image 797
Daniel Hilgarth Avatar asked Apr 20 '11 07:04

Daniel Hilgarth


1 Answers

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...

like image 169
Daniel Hilgarth Avatar answered Sep 28 '22 00:09

Daniel Hilgarth