Skip to content
This repository has been archived by the owner on Jun 21, 2023. It is now read-only.

Commit

Permalink
Merge pull request #98 from github/shana/uiprovider-caching
Browse files Browse the repository at this point in the history
Caching the UIProvider
  • Loading branch information
haacked committed Sep 22, 2015
2 parents 067be61 + 6ef6caa commit df25d49
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/GitHub.Exports/Extensions/VSExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,26 @@ namespace GitHub.Extensions
{
public static class VSExtensions
{
static IUIProvider cachedUIProvider = null;

public static T TryGetService<T>(this IServiceProvider serviceProvider) where T : class
{
return serviceProvider.TryGetService(typeof(T)) as T;
}

public static object TryGetService(this IServiceProvider serviceProvider, Type type)
{
if (cachedUIProvider != null && type == typeof(IUIProvider))
return cachedUIProvider;

var ui = serviceProvider as IUIProvider;
if (ui != null)
return ui.TryGetService(type);
else
{
try
{
return serviceProvider.GetService(type);
return GetServiceAndCache(serviceProvider, type, ref cachedUIProvider);
}
catch (Exception ex)
{
Expand All @@ -33,20 +38,42 @@ public static object TryGetService(this IServiceProvider serviceProvider, Type t

public static T GetService<T>(this IServiceProvider serviceProvider)
{
return (T)serviceProvider.GetService(typeof(T));
if (cachedUIProvider != null && typeof(T) == typeof(IUIProvider))
return (T)cachedUIProvider;

return (T)GetServiceAndCache(serviceProvider, typeof(T), ref cachedUIProvider);
}

public static T GetExportedValue<T>(this IServiceProvider serviceProvider)
{
if (cachedUIProvider != null && typeof(T) == typeof(IUIProvider))
return (T)cachedUIProvider;

var ui = serviceProvider as IUIProvider;
return ui != null
? ui.GetService<T>()
: VisualStudio.Services.ComponentModel.DefaultExportProvider.GetExportedValue<T>();
: GetExportedValueAndCache<T, IUIProvider>(ref cachedUIProvider);
}

public static ITeamExplorerSection GetSection(this IServiceProvider serviceProvider, Guid section)
{
return serviceProvider?.GetService<ITeamExplorerPage>()?.GetSection(section);
}

static object GetServiceAndCache<CacheType>(IServiceProvider provider, Type type, ref CacheType cache)
{
var ret = provider.GetService(type);
if (type == typeof(CacheType))
cache = (CacheType)ret;
return ret;
}

static T GetExportedValueAndCache<T, CacheType>(ref CacheType cache)
{
var ret = VisualStudio.Services.ComponentModel.DefaultExportProvider.GetExportedValue<T>();
if (typeof(T) == typeof(CacheType))
cache = (CacheType)(object)ret;
return ret;
}
}
}

0 comments on commit df25d49

Please sign in to comment.