Specify apartment state to use when instantiating

2019-01-19 22:59发布

问题:

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!

回答1:

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



标签: c# .net com com+