Skip to content

Instantly share code, notes, and snippets.

@sharwell
Created August 31, 2012 09:24
Show Gist options
  • Save sharwell/3550733 to your computer and use it in GitHub Desktop.
Save sharwell/3550733 to your computer and use it in GitHub Desktop.
MEF support for the Output Window in Visual Studio 2010: ServiceProviderExtensions
namespace JavaLanguageService.Extensions
{
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
public static class ServiceProviderExtensions
{
public static TServiceInterface TryGetGlobalService<TServiceClass, TServiceInterface>(this IOleServiceProvider sp)
where TServiceInterface : class
{
Contract.Requires<NullReferenceException>(sp != null);
Guid guidService = typeof(TServiceInterface).GUID;
Guid riid = typeof(TServiceInterface).GUID;
IntPtr obj = IntPtr.Zero;
int result = ErrorHandler.CallWithCOMConvention(() => sp.QueryService(ref guidService, ref riid, out obj));
if (ErrorHandler.Failed(result) || obj == IntPtr.Zero)
return null;
try
{
TServiceInterface service = (TServiceInterface)Marshal.GetObjectForIUnknown(obj);
return service;
}
finally
{
Marshal.Release(obj);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment