views:

28

answers:

0

When creating an out-of-process COM server in C# as documented in Microsoft's All-In-One code sample: CSExeCOMServer, it seems difficult to control the threading model of objects that are created in the server (by a client).

The object being created needs to be in an STA due to the fact that it uses WPF objects, and it's factory is being registered as demonstrated on line 95 of ExeCOMServer.cs and pasted below...

private void PreMessageLoop()
{
    //
    // Register the COM class factories.
    // 

    Guid clsidSimpleObj = new Guid(SimpleObject.ClassId);

    // Register the SimpleObject class object
    int hResult = COMNative.CoRegisterClassObject(
        ref clsidSimpleObj,                 // CLSID to be registered
        new SimpleObjectClassFactory(),     // Class factory
        CLSCTX.LOCAL_SERVER,                // Context to run
        REGCLS.MULTIPLEUSE | REGCLS.SUSPENDED,
        out _cookieSimpleObj);
    if (hResult != 0)
    {
        throw new ApplicationException(
        "CoRegisterClassObject failed w/err 0x" + hResult.ToString("X"));
    }

However, the CreateInstance function is Always called in a new thread which is in an MTA. It doesn't seem to matter that the main thread of the local server is marked (and verified) as an STA thread.

All material on the matter that has been found intimates that the apartment of the created objects should match the apartment of the thread in which the factory was registered. In fact, this seems to be the case when using an ATL COM server (mixed with Managed C++ to create the objects), but this method appears to be injecting a new thread in to the work flow who's intialization parameters, particularly the COM threading model, do not appear to be changeable.

Has anyone solved this issue without resorting to a COM server written largely in unmanaged code.