Search code examples
.netcominteropcom-interopexcel-interop

Excel Interop instantiates cross apartment proxy in STA thread


From what I understand from apartments in .NET, when we create a apartment threaded COM object inside a STA thread we should get a reference to the real object, not the cross-apartment proxy.

[TestMethod]
Public void ExcelShouldNotBeMarshalled()
{
     var excelApp = new Microsoft.Office.Interop.Excel.Application();
     if (excelApp is IMarshal)
         throw new Exception(“Should not be a proxy as we are running this in a STA and registry ThreadingModel is empty”);
}

I cannot get this to work with any combination of ThreadingModel I try.

Is there anything I could be missing?

Why proxies are not okay from me? I want my test to run as closest as possible to the real app. When the application is running as Excel add-in, then I get non proxy references and everything work as a charm, but in tests, events callbacks do pump to random MTA threads instead of pumping back in the UI Thead.


Solution

  • As Simon replied in the comments, Excel runs in a separate process and the ‘new Application’ part of the code will always give a proxy - no matter what theading model.

    To avoid proxy objects and run the test just like in production, Joseph proposed in the comments to run the test using VBA, calling .Net methods. I found it suitable so I implemented using xUnit capabilities to customize test execution and handle the VBA invoking my test methods. It solves my proxy related problems and as a plus, improves test speed.

    Thanks to all involved!