Created
August 31, 2012 09:24
-
-
Save sharwell/3550733 to your computer and use it in GitHub Desktop.
MEF support for the Output Window in Visual Studio 2010: ServiceProviderExtensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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