I have this code in a C# add-in for the VBE (emphasis "VBE": it's not a MS-Office add-in):
public abstract class HostApplicationBase<TApplication> : IHostApplication
where TApplication : class
{
protected readonly TApplication Application;
protected HostApplicationBase(string applicationName)
{
Application = (TApplication)Marshal.GetActiveObject(applicationName + ".Application");
}
Where TApplication is a MS-Office interop Application class, for example, a Microsoft.Office.Interop.Excel.Application type; here the applicationName parameter would be "Excel" for, well, Excel.
The problem is that Marshal.GetActiveObject seems to only ever return the first instance created, and that's not necessarily the instance that's hosting the current VBE environment, and this causes issues.
How can I get ahold of the actual host application instance?