0

I'm trying to test how my t4 template generates outside the context of my addon. I've looked at https://msdn.microsoft.com/en-us/library/68shb4dw.aspx and https://msdn.microsoft.com/en-us/library/bb166401.aspx to get the DTE and the IServicePRovider. However there's a strange behavior while on the context of a UnitTest the following happens:

var dte = Marshal.GetActiveObject("VisualStudio.DTE.15.0") as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
System.IServiceProvider serviceProvider =  new Microsoft.VisualStudio.Shell.ServiceProvider(dte);

// This returns a valid System.__ComObject (not null)
object serviceInstance = serviceProvider.GetService(typeof(Microsoft.VisualStudio.TextTemplating.VSHost.STextTemplating));

// Throws an exception
var textTemplating = (Microsoft.VisualStudio.TextTemplating.VSHost.STextTemplating)serviceInstance;

The exception text:

System.InvalidCastException: 'Unable to cast COM of type 'System.__ComObject' to interface type 'Microsoft.VisualStudio.TextTemplating.VSHost.STextTemplating'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{508349B6-6B84-4DF5-91F0-309BEEBAD82D}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x800040002 (E_NOINTERFACE)). (Microsoft.VisualStudio.OLE.Interop)

I've tried querying the IServiceProvider with the specific STextTemplate GUID and it returns HRESULT = 0, so this seems quite odd.

Thank you!

  • 1
    The VS extensibility interface was designed to be used by add-ins. But this is not an add-in that runs in-process like they normally do, you are trying to use it out-of-process. Now something very nontrivial needs to happen, VS must provide a proxy to the interface so the call can be made across the process boundary. The exception tells you that it doesn't have one. Something you can verify with Regedit.exe. That's where it ends, consider an add-in and/or reporting the issue at Microsoft. – Hans Passant Aug 27 '17 at 13:48
  • What happens if you cast it in the same line? Like 'object serviceInstance = serviceProvider.GetService(typeof(Microsoft.VisualStudio.TextTemplating.VSHost.STextTemplating)) as Microsoft.VisualStudio.TextTemplating.VSHost.STextTemplating; – Nikolaus Aug 27 '17 at 13:49
  • As @HansPassant said. Your code works just fine if running in the context of a Visual Studio package. – Hugo Quintela Ribeiro Aug 28 '17 at 09:19

0 Answers0