I can use an out-of-process COM server that is not registered with C# dynamic, and this works fine, but I cannot get events to work.
My code basically is something like this:
Process.Start("path\\to\\comserver.exe", "-embedding");
Thread.Sleep(1000);
Type serverType = Type.GetTypeFromCLSID(new Guid("..."));
dynamic c = Activator.CreateInstance(serverType);
Console.WriteLine(c.SomeProperty); // works
Console.WriteLine(c.SomeMethod(42)); // works
// c.SomeEvent += Handler; // works only with COM registration
var cpc = (IConnectionPointContainer) c;
Guid guidOfIServerEvents = ...;
cpc.FindConnectionPoint(ref guidOfIServerEvents, out IConnectionPoint? ppCP);
EventsSinkHelper sinkHelper = new();
ppCP.Advise(sinkHelper, out int cookie); // COMException 0x80040202 without COM registration
// ...
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("...")]
interface IServerEvents
{
[DispId(1)]
void SomeEvent();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("... (a different GUID)")]
public sealed class EventsSinkHelper : IServerEvents
{
public void SomeEvent() { /* ... */ }
}
This works perfectly when the COM server is registered, but when it is not registered, calling Advise results in a COMException with error 0x80040202.
Running everything in an STA thread behaves the same way.
I understand that this scenario is not supported and may stop working at any time, but it is extremely handy for testing, especially for unit tests.
How could I make events work?