Create Out-Of-Process COM in C#/.Net?

2020-01-26 05:01发布

问题:

I need to create an out-of-process COM server (.exe) in C# that will be accessed by multiple other processes on the same box. The component has to be a single process because it will cache the information it provides to its consumers in memory.

Note: the processes that will access my COM Server are mostly Matlab processes, thus the necessity for a COM interface.

I have seen threads regarding creating in-process COM components in .Net on stack overflow (Create COM ...) and on the web, but am having a hard time to find a way to create out-of-process components with .Net.

How is this achievable? Any suggested references?

Thanks.

回答1:

One option is serviced components - i.e. host it in COM+ as the shell exe. See also the howto here.



回答2:

We too had some issues many years ago with regasm and running the COM class as a Local EXE Server.

This is a bit of a hack and I'd welcome any suggestions to make it more elegant. It was implemented for a project back in the .NET 1.0 days and has not been touched since then!

Basically it performs a regasm style of registration each time the application starts (it needs to be run once to make registry entries before the COM object is instantiated in the COM container application).

I've copied the following important bits from our implementation and renamed a few classes to illustrate the example.

The following method is called from the Form Loaded event to register the COM class(renamed to MyCOMClass for this example)

private void InitialiseCOM()
    {
        System.Runtime.InteropServices.RegistrationServices services = new System.Runtime.InteropServices.RegistrationServices();
        try
        {
            System.Reflection.Assembly ass = Assembly.GetExecutingAssembly();
            services.RegisterAssembly(ass, System.Runtime.InteropServices.AssemblyRegistrationFlags.SetCodeBase);
            Type t = typeof(MyCOMClass);
            try
            {
                Registry.ClassesRoot.DeleteSubKeyTree("CLSID\\{" + t.GUID.ToString() + "}\\InprocServer32");
            }
            catch(Exception E)
            {
                Log.WriteLine(E.Message);
            }

            System.Guid GUID = t.GUID;
            services.RegisterTypeForComClients(t, ref GUID );
        }
        catch ( Exception e )
        {
            throw new Exception( "Failed to initialise COM Server", e );
        }
    }

For the type in question, MyCOMObject, will need some special attributes to be COM compatible. One important attribute is to specify a fixed GUID otherwise each time you compile the registry will fill up with orphaned COM GUIDs. You can use the Tools menu in VisualStudio to create you a unique GUID.

  [GuidAttribute("D26278EA-A7D0-4580-A48F-353D1E455E50"),
  ProgIdAttribute("My PROGID"),
  ComVisible(true),
  Serializable]
  public class MyCOMClass : IAlreadyRegisteredCOMInterface
  {
    public void MyMethod()
    {
    }

    [ComRegisterFunction]
    public static void RegisterFunction(Type t)
    {
      AttributeCollection attributes = TypeDescriptor.GetAttributes(t);
      ProgIdAttribute ProgIdAttr = attributes[typeof(ProgIdAttribute)] as ProgIdAttribute;

      string ProgId = ProgIdAttr != null ? ProgIdAttr.Value : t.FullName;

      GuidAttribute GUIDAttr = attributes[typeof(GuidAttribute)] as GuidAttribute;
      string GUID = "{" + GUIDAttr.Value + "}";

      RegistryKey localServer32 = Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\\{0}\\LocalServer32", GUID));
      localServer32.SetValue(null, t.Module.FullyQualifiedName);

      RegistryKey CLSIDProgID = Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\\{0}\\ProgId", GUID));
      CLSIDProgID.SetValue(null, ProgId);

      RegistryKey ProgIDCLSID = Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\\{0}", ProgId));
      ProgIDCLSID.SetValue(null, GUID);

      //Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\\{0}\\Implemented Categories\\{{63D5F432-CFE4-11D1-B2C8-0060083BA1FB}}", GUID));
      //Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\\{0}\\Implemented Categories\\{{63D5F430-CFE4-11d1-B2C8-0060083BA1FB}}", GUID));
      //Registry.ClassesRoot.CreateSubKey(String.Format("CLSID\\{0}\\Implemented Categories\\{{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}}", GUID));
    }

    [ComUnregisterFunction]
    public static void UnregisterFunction(Type t)
    {
      AttributeCollection attributes = TypeDescriptor.GetAttributes(t);
      ProgIdAttribute ProgIdAttr = attributes[typeof(ProgIdAttribute)] as ProgIdAttribute;

      string ProgId = ProgIdAttr != null ? ProgIdAttr.Value : t.FullName;

      Registry.ClassesRoot.DeleteSubKeyTree("CLSID\\{" + t.GUID + "}");
      Registry.ClassesRoot.DeleteSubKeyTree("CLSID\\" + ProgId);
    }

  }

The InitialiseCOM method in the main form uses RegistrationServices to register the type. The framework then uses reflection to find the method marked with the ComRegisterFunction attribute and calls that function with the type being registered.

The ComRegisterFunction marked method, hand creates the registry settings for a Local EXE Server COM object and this can be compared with regasm if you use REGEDIT and find the keys in question.

I've commented out the three \\Registry.ClassesRoot.CreateSubKey method calls as this was another reason we needed to register the type ourselves as this was an OPC server and third party OPC clients use these implemented categories to scan for compatible OPC servers. REGASM would not add these in for us unless we did the work ourselves.

You can easily see how this works if you put break points on the functions as it is starting.

Our implementation used an interface that was already registered with COM. For your application you will either need to :-

  1. Extend the registration methods listed above to register the interface with COM
  2. Or create a separate DLL with the interface definition and then export that interface definition to a type library and register that as discussed in the StackOverflow link you added in the question.


回答3:

The official answer is in KB article How to develop an out-of-process COM component by using Visual C++, Visual C#, or Visual Basic .NET.



回答4:

IMO, one of the ways through which this can be done is to create a normal COM Dll as per the method you mentioned in the link and then after registering your COM dll, change it to a surrogate DLL. This can be done very easily through OLEView utility, although you can do it manually as well by changing registry entries as well through the method mentioned at http://msdn.microsoft.com/en-us/library/ms686606(VS.85).aspx.

By making this a surrogate DLL, it will run in it's own dllhost.exe and hence will be out-of-process.



回答5:

ActiveX.NET, is a true Out-Of-Proc (EXE) COM Server implementation in C#.NET. This one has a cleaner implementation compared to the original CSExeCOMServer, published in Code.MSDN.

ActiveX.NET has features like it does use a .NET Message Pump (instead of native) and uses MEF Plugin model, so that the EXE Server is decoupled and can be shared among multiple COM Plugins, which can be developed independently



回答6:

You can use RegistrationServices.RegisterTypeForComClients, which is the managed equivalent of CoRegisterClassObject - for sample code see here.



回答7:

It could be done using umanaged ATL framework and plumbing it with the managed code (simple by changing the result project properties to /clr).

Here are illustrative snippets:

.H-part:

\#include < vcclr.h >

\#using < MyCSharpModule.dll >

using namespace System;

class ATL_NO_VTABLE MyCSharpProxyServer :
    public CComObjectRootEx< CComMultiThreadModel >,

.....

{

      HRESULT FinalConstruct();

      STDMETHODIMP LoadMyFile(BSTR FileName);
.....
      gcroot<MyCSNamespace::MyCSharpClass^> m_CSClass;

}

.CPP-part:

using namespace System::Collections;

using namespace MyCSNamespace;

HRESULT MyCSharpProxyServer::FinalConstruct()
{

    m_CSClass = gcnew MyCSharpClass();

}

STDMETHODIMP MyCSharpProxyServer::LoadMyFile(BSTR FileName)
{

    try {
       int hr = m_CSClass->LoadFile(gcnew String( FileName));
        return hr;
    }
    catch( Exception^ e )  {
        return E_FAIL;
    }
}

The C# part (MyCSharpClass class) lives in a separate project with output type Class Library.



回答8:

The visual studio project "CSExeCOMServer" that you can find here (All-in-One), gives a full example.



回答9:

Use the flag REGCLS_MULTIPLEUSE with CoRegisterClassObject() to make the coclass a multiuse class. Here is more info: http://support.microsoft.com/kb/169321.



标签: c# com