diff --git a/src/NuGet.Clients/NuGet.Console/PowerConsoleToolWindow.cs b/src/NuGet.Clients/NuGet.Console/PowerConsoleToolWindow.cs index 2f710b9b757..1fb935b35b0 100644 --- a/src/NuGet.Clients/NuGet.Console/PowerConsoleToolWindow.cs +++ b/src/NuGet.Clients/NuGet.Console/PowerConsoleToolWindow.cs @@ -683,7 +683,7 @@ private IOutputConsole VSOutputConsole { _vsOutputConsole = NuGetUIThreadHelper.JoinableTaskFactory.Run(async () => { - var consoleProvider = await ServiceLocator.GetComponentModelServiceAsync(); + var consoleProvider = await ServiceLocator.GetInstanceAsync(); if (null != consoleProvider) { return await consoleProvider.CreatePackageManagerConsoleAsync(); @@ -703,7 +703,7 @@ private IConsoleStatus ConsoleStatus { if (_consoleStatus == null) { - _consoleStatus = ServiceLocator.GetComponentModelService(); + _consoleStatus = ServiceLocator.GetInstance(); Debug.Assert(_consoleStatus != null); } diff --git a/src/NuGet.Clients/NuGet.Console/Xamls/ConsoleContainer.xaml.cs b/src/NuGet.Clients/NuGet.Console/Xamls/ConsoleContainer.xaml.cs index ea010a19ed5..e013f26c60d 100644 --- a/src/NuGet.Clients/NuGet.Console/Xamls/ConsoleContainer.xaml.cs +++ b/src/NuGet.Clients/NuGet.Console/Xamls/ConsoleContainer.xaml.cs @@ -48,9 +48,9 @@ await System.Threading.Tasks.Task.Run( Assumes.NotNull(_solutionManager); - var productUpdateService = ServiceLocator.GetComponentModelService(); - var packageRestoreManager = ServiceLocator.GetComponentModelService(); - var deleteOnRestartManager = ServiceLocator.GetComponentModelService(); + var productUpdateService = ServiceLocator.GetInstance(); + var packageRestoreManager = ServiceLocator.GetInstance(); + var deleteOnRestartManager = ServiceLocator.GetInstance(); var shell = ServiceLocator.GetGlobalService(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Cmdlets/UninstallPackageCommand.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Cmdlets/UninstallPackageCommand.cs index ebbfcbdebf1..7df74c0b7dc 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Cmdlets/UninstallPackageCommand.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Cmdlets/UninstallPackageCommand.cs @@ -25,8 +25,8 @@ public class UninstallPackageCommand : NuGetPowerShellBaseCommand public UninstallPackageCommand() { - _deleteOnRestartManager = ServiceLocator.GetComponentModelService(); - _lockService = ServiceLocator.GetComponentModelService(); + _deleteOnRestartManager = ServiceLocator.GetInstance(); + _lockService = ServiceLocator.GetInstance(); } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs index 2109fbc331a..dc5b9178436 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs @@ -68,14 +68,14 @@ public abstract class NuGetPowerShellBaseCommand : PSCmdlet, IPSNuGetProjectCont protected NuGetPowerShellBaseCommand() { - _sourceRepositoryProvider = ServiceLocator.GetComponentModelService(); - ConfigSettings = ServiceLocator.GetComponentModelService(); - VsSolutionManager = ServiceLocator.GetComponentModelService(); + _sourceRepositoryProvider = ServiceLocator.GetInstance(); + ConfigSettings = ServiceLocator.GetInstance(); + VsSolutionManager = ServiceLocator.GetInstance(); DTE = ServiceLocator.GetInstance(); - SourceControlManagerProvider = ServiceLocator.GetComponentModelService(); - _commonOperations = ServiceLocator.GetComponentModelService(); - PackageRestoreManager = ServiceLocator.GetComponentModelService(); - _deleteOnRestartManager = ServiceLocator.GetComponentModelService(); + SourceControlManagerProvider = ServiceLocator.GetInstance(); + _commonOperations = ServiceLocator.GetInstance(); + PackageRestoreManager = ServiceLocator.GetInstance(); + _deleteOnRestartManager = ServiceLocator.GetInstance(); var logger = new LoggerAdapter(this); PackageExtractionContext = new PackageExtractionContext( diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs index 5b39b592606..660d831d4af 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs @@ -29,8 +29,8 @@ public class PackageActionBaseCommand : NuGetPowerShellBaseCommand public PackageActionBaseCommand() { - _deleteOnRestartManager = ServiceLocator.GetComponentModelService(); - _lockService = ServiceLocator.GetComponentModelService(); + _deleteOnRestartManager = ServiceLocator.GetInstance(); + _lockService = ServiceLocator.GetInstance(); } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/GeneralOptionControl.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/GeneralOptionControl.cs index 148b38bd865..4a9d55be87c 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/GeneralOptionControl.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/GeneralOptionControl.cs @@ -25,8 +25,8 @@ public partial class GeneralOptionControl : UserControl public GeneralOptionControl() { InitializeComponent(); - _settings = ServiceLocator.GetComponentModelService(); - _outputConsoleLogger = ServiceLocator.GetComponentModelService(); + _settings = ServiceLocator.GetInstance(); + _outputConsoleLogger = ServiceLocator.GetInstance(); _localsCommandRunner = new LocalsCommandRunner(); AutoScroll = true; Debug.Assert(_settings != null); @@ -150,7 +150,7 @@ private void OnLocalsCommandButtonOnClick(object sender, EventArgs e) { UpdateLocalsCommandStatusText(string.Format(Resources.ShowMessage_LocalsCommandWorking), visibility: true); var arguments = new List { "all" }; - var settings = ServiceLocator.GetComponentModelService(); + var settings = ServiceLocator.GetInstance(); var logError = new LocalsArgs.Log(LogError); var logInformation = new LocalsArgs.Log(LogInformation); var localsArgs = new LocalsArgs(arguments, settings, logInformation, logError, clear: true, list: false); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/OptionsPageBase.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/OptionsPageBase.cs index 50485043dd2..4360c41343d 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/OptionsPageBase.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/Options/OptionsPageBase.cs @@ -45,7 +45,7 @@ private void OnTimerTick(object sender, EventArgs e) timer.Stop(); timer.Dispose(); - var optionsPageActivator = ServiceLocator.GetComponentModelService(); + var optionsPageActivator = ServiceLocator.GetInstance(); if (optionsPageActivator != null) { optionsPageActivator.NotifyOptionsDialogClosed(); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs index 4fc357a4c84..e3deead508f 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs @@ -86,7 +86,7 @@ private async ValueTask InitializeAsync(PackageManagerModel model, INuGetUILogge Model = model; _uiLogger = uiLogger; - Settings = await ServiceLocator.GetComponentModelServiceAsync(); + Settings = await ServiceLocator.GetInstanceAsync(); _windowSearchHostFactory = await ServiceLocator.GetGlobalServiceAsync(); _serviceBroker = model.Context.ServiceBroker; @@ -882,7 +882,7 @@ private async Task GetUseRecommendedPackagesAsync(PackageLoadContext loadC _recommendPackages = true; } - NuGetExperimentationService = await ServiceLocator.GetComponentModelServiceAsync(); + NuGetExperimentationService = await ServiceLocator.GetInstanceAsync(); // Check for A/B experiment here. For control group, return false instead of _recommendPackages if (IsRecommenderFlightEnabled(NuGetExperimentationService)) { diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetPackageSearchService.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetPackageSearchService.cs index 073265181df..09b24ffaeb2 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetPackageSearchService.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetPackageSearchService.cs @@ -335,7 +335,7 @@ private async ValueTask GetInstalledAndTransiti CancellationToken cancellationToken) { var logger = new VisualStudioActivityLogger(); - var uiLogger = await ServiceLocator.GetComponentModelServiceAsync(); + var uiLogger = ServiceLocator.GetInstance(); var packageFeeds = (mainFeed: (IPackageFeed?)null, recommenderFeed: (IPackageFeed?)null); if (itemFilter == ItemFilter.All && recommendPackages == false) @@ -414,7 +414,7 @@ private async Task> GetGlobalPackageFolderReposi private async Task GetPackagesFolderSourceRepositoryAsync() { IVsSolutionManager solutionManager = await _sharedServiceState.SolutionManager.GetValueAsync(); - ISettings settings = await ServiceLocator.GetComponentModelServiceAsync(); + ISettings settings = ServiceLocator.GetInstance(); return _sharedServiceState.SourceRepositoryProvider.CreateRepository( new PackageSource(PackagesFolderPathUtility.GetPackagesFolderPath(solutionManager, settings)), diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectManagerService.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectManagerService.cs index e431f47aba4..051ae2130bc 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectManagerService.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectManagerService.cs @@ -349,7 +349,7 @@ await CatchAndRethrowExceptionAsync(async () => try { - projectContext = await ServiceLocator.GetComponentModelServiceAsync(); + projectContext = await ServiceLocator.GetInstanceAsync(); Assumes.NotNull(projectContext); @@ -418,7 +418,7 @@ public async ValueTask> GetInstallActionsAsync( Assumes.NotNullOrEmpty(sourceRepositories); - INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync(); + INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync(); IReadOnlyList projects = await GetProjectsAsync(projectIds, cancellationToken); var resolutionContext = new ResolutionContext( @@ -471,7 +471,7 @@ public async ValueTask> GetUninstallActionsAsync( return await CatchAndRethrowExceptionAsync(async () => { - INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync(); + INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync(); IReadOnlyList projects = await GetProjectsAsync(projectIds, cancellationToken); var projectActions = new List(); @@ -541,7 +541,7 @@ public async ValueTask> GetUpdateActionsAsync( } } - INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync(); + INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync(); IReadOnlyList projects = await GetProjectsAsync(projectIds, cancellationToken); var resolutionContext = new ResolutionContext( diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectUpgraderService.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectUpgraderService.cs index 9704e81d8f9..485fe186918 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectUpgraderService.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/NuGetProjectUpgraderService.cs @@ -150,7 +150,7 @@ public async ValueTask UninstallPackagesAsync( NuGetPackageManager packageManager = await _state.GetPackageManagerAsync(cancellationToken); Assumes.NotNull(packageManager); - INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync(); + INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync(); Assumes.NotNull(projectContext); await packageManager.ExecuteNuGetProjectActionsAsync( @@ -186,7 +186,7 @@ public async ValueTask InstallPackagesAsync( NuGetPackageManager packageManager = await _state.GetPackageManagerAsync(cancellationToken); Assumes.NotNull(packageManager); - INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync(); + INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync(); Assumes.NotNull(projectContext); await packageManager.ExecuteBuildIntegratedProjectActionsAsync( diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/SharedServiceState.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/SharedServiceState.cs index 0fa7862836c..d2cf214308a 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/SharedServiceState.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Services/SharedServiceState.cs @@ -27,7 +27,7 @@ internal SharedServiceState(ISourceRepositoryProvider sourceRepositoryProvider) SourceRepositoryProvider.PackageSourceProvider.PackageSourcesChanged += PackageSourcesChanged; SolutionManager = new AsyncLazy( - ServiceLocator.GetComponentModelServiceAsync, + ServiceLocator.GetInstanceAsync, NuGetUIThreadHelper.JoinableTaskFactory); SourceRepositories = new AsyncLazy>( @@ -41,15 +41,15 @@ internal SharedServiceState(ISourceRepositoryProvider sourceRepositoryProvider) public static async ValueTask CreateAsync(CancellationToken cancellationToken) { - var sourceRepositoryProvider = await ServiceLocator.GetComponentModelServiceAsync(); + var sourceRepositoryProvider = await ServiceLocator.GetInstanceAsync(); return new SharedServiceState(sourceRepositoryProvider); } public async ValueTask GetPackageManagerAsync(CancellationToken cancellationToken) { - IDeleteOnRestartManager deleteOnRestartManager = await ServiceLocator.GetComponentModelServiceAsync(); - ISettings settings = await ServiceLocator.GetComponentModelServiceAsync(); + IDeleteOnRestartManager deleteOnRestartManager = await ServiceLocator.GetInstanceAsync(); + ISettings settings = await ServiceLocator.GetInstanceAsync(); IVsSolutionManager solutionManager = await SolutionManager.GetValueAsync(cancellationToken); return new NuGetPackageManager( diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs index 92523b7ab48..9e7e844600e 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs @@ -86,7 +86,7 @@ public static async Task IsNuGetProjectUpgradeableAsync(NuGetProject nuGet private static async Task GetNuGetProject(Project envDTEProject) { - var solutionManager = await ServiceLocator.GetComponentModelServiceAsync(); + var solutionManager = ServiceLocator.GetInstance(); var projectSafeName = await envDTEProject.GetCustomUniqueNameAsync(); var nuGetProject = await solutionManager.GetNuGetProjectAsync(projectSafeName); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/ProjectRetargetingUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/ProjectRetargetingUtility.cs index 8e02c2ef325..e09cdb6a7f5 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/ProjectRetargetingUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/ProjectRetargetingUtility.cs @@ -43,7 +43,7 @@ public static async Task> GetPackagesToBeReinstalled(NuGe if (installedRefs != null && installedRefs.Any()) { var targetFramework = project.GetMetadata(NuGetProjectMetadataKeys.TargetFramework); - return await GetPackagesToBeReinstalledAsync(targetFramework, installedRefs); + return GetPackagesToBeReinstalled(targetFramework, installedRefs); } return new List(); @@ -55,16 +55,16 @@ public static async Task> GetPackagesToBeReinstalled(NuGe /// Current target framework of the project /// List of package references in the project from which packages to be reinstalled are determined /// List of package identities to be reinstalled - public static async Task> GetPackagesToBeReinstalledAsync(NuGetFramework projectFramework, IEnumerable packageReferences) + public static List GetPackagesToBeReinstalled(NuGetFramework projectFramework, IEnumerable packageReferences) { Debug.Assert(projectFramework != null); Debug.Assert(packageReferences != null); var packagesToBeReinstalled = new List(); - var sourceRepositoryProvider = await ServiceLocator.GetComponentModelServiceAsync(); - var solutionManager = await ServiceLocator.GetComponentModelServiceAsync(); - var settings = await ServiceLocator.GetComponentModelServiceAsync(); - var deleteOnRestartManager = await ServiceLocator.GetComponentModelServiceAsync(); + var sourceRepositoryProvider = ServiceLocator.GetInstance(); + var solutionManager = ServiceLocator.GetInstance(); + var settings = ServiceLocator.GetInstance(); + var deleteOnRestartManager = ServiceLocator.GetInstance(); var packageManager = new NuGetPackageManager( sourceRepositoryProvider, settings, diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/SettingsHelper.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/SettingsHelper.cs index 933607e1c58..90a43560221 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/SettingsHelper.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/SettingsHelper.cs @@ -24,7 +24,7 @@ public static class SettingsHelper /// public static void Set(string property, string value) { - var settings = ServiceLocator.GetComponentModelService(); + var settings = ServiceLocator.GetInstance(); var packageRestoreConsent = new PackageRestoreConsent(settings); if (string.Equals(property, "PackageRestoreConsentGranted", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/NuGet.Clients/NuGet.Tools/NuGetBrokeredServiceFactory.cs b/src/NuGet.Clients/NuGet.Tools/NuGetBrokeredServiceFactory.cs index a6fd081713e..e187850d0cf 100644 --- a/src/NuGet.Clients/NuGet.Tools/NuGetBrokeredServiceFactory.cs +++ b/src/NuGet.Clients/NuGet.Tools/NuGetBrokeredServiceFactory.cs @@ -203,11 +203,11 @@ private async ValueTask CreatePackageFileServiceAsync( } private async Task InitializeAsync() { - _lazySettings = new AsyncLazy(ServiceLocator.GetComponentModelServiceAsync, ThreadHelper.JoinableTaskFactory); - _lazySolutionManager = new AsyncLazy(ServiceLocator.GetComponentModelServiceAsync, ThreadHelper.JoinableTaskFactory); + _lazySettings = new AsyncLazy(ServiceLocator.GetInstanceAsync, ThreadHelper.JoinableTaskFactory); + _lazySolutionManager = new AsyncLazy(ServiceLocator.GetInstanceAsync, ThreadHelper.JoinableTaskFactory); _projectManagerServiceSharedState = new NuGetProjectManagerServiceState(); _sharedServiceState = await SharedServiceState.CreateAsync(CancellationToken.None); - _lazyTelemetryProvider = new AsyncLazy(ServiceLocator.GetComponentModelServiceAsync, ThreadHelper.JoinableTaskFactory); + _lazyTelemetryProvider = new AsyncLazy(ServiceLocator.GetInstanceAsync, ThreadHelper.JoinableTaskFactory); } } } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs index 78c1f43331b..05469d04e65 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs @@ -118,7 +118,7 @@ public static async TaskExpandedNodes GetAllExpandedNodesAsync() // this operation needs to execute on UI thread await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - var dte = await ServiceLocator.GetInstanceAsync(); + var dte = ServiceLocator.GetInstance(); var projects = dte.Solution.Projects; var results = new Dictionary>(StringComparer.OrdinalIgnoreCase); @@ -139,7 +139,7 @@ public static async Task CollapseAllNodesAsync(IDictionary(); + var dte = ServiceLocator.GetInstance(); var projects = dte.Solution.Projects; foreach (var project in projects.Cast()) @@ -157,7 +157,7 @@ public static async Task CollapseAllNodesAsync(IDictionary> GetExpandedProjectHierarchyItemsAsync(EnvDTE.Project project) { var projectHierarchyItem = await VsHierarchyItem.FromDteProjectAsync(project); - var solutionExplorerWindow = await GetSolutionExplorerHierarchyWindowAsync(); + var solutionExplorerWindow = GetSolutionExplorerHierarchyWindow(); if (solutionExplorerWindow == null) { @@ -192,7 +192,7 @@ await projectHierarchyItem.WalkDepthFirstAsync( private static async Task CollapseProjectHierarchyItemsAsync(EnvDTE.Project project, ISet ignoredHierarcyItems) { var projectHierarchyItem = await VsHierarchyItem.FromDteProjectAsync(project); - var solutionExplorerWindow = await GetSolutionExplorerHierarchyWindowAsync(); + var solutionExplorerWindow = GetSolutionExplorerHierarchyWindow(); if (solutionExplorerWindow == null) { @@ -252,11 +252,10 @@ private static IVsUIHierarchy AsVsUIHierarchy(VsHierarchyItem hierarchyItem) return hierarchyItem.VsHierarchy as IVsUIHierarchy; } - private static async Task GetSolutionExplorerHierarchyWindowAsync() + private static IVsUIHierarchyWindow GetSolutionExplorerHierarchyWindow() { - var serviceProvider = await ServiceLocator.GetInstanceAsync(); return VsShellUtilities.GetUIHierarchyWindow( - serviceProvider, + ServiceLocator.GetInstance(), new Guid(VsWindowKindSolutionExplorer)); } } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/ServiceLocator.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/ServiceLocator.cs index ec98419a37a..9382abe4748 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/ServiceLocator.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/ServiceLocator.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Threading.Tasks; using EnvDTE; @@ -11,6 +12,7 @@ using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; +using Task = System.Threading.Tasks.Task; using VsServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace NuGet.VisualStudio @@ -39,27 +41,17 @@ public static TService GetInstanceSafe() where TService : class } } - /// public static TService GetInstance() where TService : class { return NuGetUIThreadHelper.JoinableTaskFactory.Run(GetInstanceAsync); } - /// - /// Fetches a service that may be registered with the DTE, MEF or the VS service provider. - /// This method may switch to the UI thread. - /// - /// - /// The instance of the service request, otherwise. - /// - /// Prefer over this requesting a MEF service. - /// A general rule is that only non-NuGet VS services should be retrieved this method. - /// public static async Task GetInstanceAsync() where TService : class { - // Try to find the service as a component model, then try dte then lastly try global service - // Per bug #2072, avoid calling GetGlobalService() from within the Initialize() method of NuGetPackage class. - // Doing so is illegal and may make VS to stop responding. As a result of that, we defer calling GetGlobalService to the last option. + // VS Threading Rule #1 + // Access to ServiceProvider and a lot of casts are performed in this method, + // and so this method can RPC into main thread. Switch to main thread explictly, since method has STA requirement + await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Special case IServiceProvider if (typeof(TService) == typeof(IServiceProvider)) @@ -68,6 +60,9 @@ public static async Task GetInstanceAsync() where TService : return (TService)serviceProvider; } + // then try to find the service as a component model, then try dte then lastly try global service + // Per bug #2072, avoid calling GetGlobalService() from within the Initialize() method of NuGetPackage class. + // Doing so is illegal and may make VS to stop responding. As a result of that, we defer calling GetGlobalService to the last option. var serviceFromDTE = await GetDTEServiceAsync(); if (serviceFromDTE != null) { @@ -121,38 +116,28 @@ public static async Task GetGlobalServiceFreeThreadedAsync - /// Fetches a MEF registered service if available. - /// This method should be called from a background thread only. - /// - /// - /// The instance of the service request, otherwise. - /// - /// This method should only be preferred when using MEF imports is not easily achievable. - /// Prefer this over when the service requesting a MEF service. - /// A general rule is that internal NuGet services should call this method over . - /// This method can be called from the UI thread, but that's unnecessary and a bad practice. Never do things that don't need the UI thread, on the UI thread. - /// - public static async Task GetComponentModelServiceAsync() where TService : class + private static async Task GetDTEServiceAsync() where TService : class { - IComponentModel componentModel = await GetGlobalServiceFreeThreadedAsync(); - return componentModel?.GetService(); + await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + var dte = await GetGlobalServiceAsync(); + return dte != null ? QueryService(dte, typeof(TService)) as TService : null; } - /// - public static TService GetComponentModelService() where TService : class + private static async Task GetComponentModelServiceAsync() where TService : class { - return NuGetUIThreadHelper.JoinableTaskFactory.Run(GetComponentModelServiceAsync); + IComponentModel componentModel = await GetGlobalServiceFreeThreadedAsync(); + return componentModel?.GetService(); } - private static async Task GetDTEServiceAsync() where TService : class + private static async Task GetServiceProviderAsync() { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var dte = await GetGlobalServiceAsync(); - return dte != null ? QueryService(dte, typeof(TService)) as TService : null; + return GetServiceProviderFromDTE(dte); } private static object QueryService(DTE dte, Type serviceType) @@ -182,13 +167,7 @@ private static object QueryService(DTE dte, Type serviceType) return service; } - private static async Task GetServiceProviderAsync() - { - await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - var dte = await GetGlobalServiceAsync(); - return GetServiceProviderFromDTE(dte); - } - + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The caller is responsible for disposing this")] private static IServiceProvider GetServiceProviderFromDTE(DTE dte) { ThreadHelper.ThrowIfNotOnUIThread(); diff --git a/src/NuGet.Clients/NuGetConsole.Host.PowerShell/PowerShellHost.cs b/src/NuGet.Clients/NuGetConsole.Host.PowerShell/PowerShellHost.cs index 7bf650deb83..c54b700e1c0 100644 --- a/src/NuGet.Clients/NuGetConsole.Host.PowerShell/PowerShellHost.cs +++ b/src/NuGet.Clients/NuGetConsole.Host.PowerShell/PowerShellHost.cs @@ -106,11 +106,11 @@ protected PowerShellHost(string name, IRestoreEvents restoreEvents, IRunspaceMan _runspaceManager = runspaceManager; // TODO: Take these as ctor arguments - _sourceRepositoryProvider = ServiceLocator.GetComponentModelService(); - _solutionManager = new Lazy(() => ServiceLocator.GetComponentModelService()); - _settings = new Lazy(() => ServiceLocator.GetComponentModelService()); - _deleteOnRestartManager = new Lazy(() => ServiceLocator.GetComponentModelService()); - _scriptExecutor = new Lazy(() => ServiceLocator.GetComponentModelService()); + _sourceRepositoryProvider = ServiceLocator.GetInstance(); + _solutionManager = new Lazy(() => ServiceLocator.GetInstance()); + _settings = new Lazy(() => ServiceLocator.GetInstance()); + _deleteOnRestartManager = new Lazy(() => ServiceLocator.GetInstance()); + _scriptExecutor = new Lazy(() => ServiceLocator.GetInstance()); _dte = new Lazy(() => ServiceLocator.GetInstance()); _sourceControlManagerProvider = new Lazy( diff --git a/src/NuGet.Clients/NuGetConsole.Host.PowerShell/ProjectExtensions.cs b/src/NuGet.Clients/NuGetConsole.Host.PowerShell/ProjectExtensions.cs index 1028f61fa18..6376a46d907 100644 --- a/src/NuGet.Clients/NuGetConsole.Host.PowerShell/ProjectExtensions.cs +++ b/src/NuGet.Clients/NuGetConsole.Host.PowerShell/ProjectExtensions.cs @@ -38,7 +38,7 @@ public static void RemoveProject(string projectName) { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - var solutionManager = await ServiceLocator.GetComponentModelServiceAsync(); + var solutionManager = ServiceLocator.GetInstance(); if (solutionManager != null) { var project = await solutionManager.GetVsProjectAdapterAsync(projectName); @@ -47,7 +47,7 @@ public static void RemoveProject(string projectName) throw new InvalidOperationException(); } - var dte = await ServiceLocator.GetInstanceAsync(); + var dte = ServiceLocator.GetInstance(); dte.Solution.Remove(project.Project); } }); diff --git a/src/NuGet.Clients/NuGetConsole.Host.PowerShell/RunspaceManager.cs b/src/NuGet.Clients/NuGetConsole.Host.PowerShell/RunspaceManager.cs index eb3795e954f..d9a9bae4231 100644 --- a/src/NuGet.Clients/NuGetConsole.Host.PowerShell/RunspaceManager.cs +++ b/src/NuGet.Clients/NuGetConsole.Host.PowerShell/RunspaceManager.cs @@ -61,8 +61,8 @@ private static Tuple CreateRunspace(IConsole co ); // this is used by the functional tests - var sourceRepositoryProvider = ServiceLocator.GetComponentModelService(); - var solutionManager = ServiceLocator.GetComponentModelService(); + var sourceRepositoryProvider = ServiceLocator.GetInstance(); + var solutionManager = ServiceLocator.GetInstance(); var sourceRepoTuple = Tuple.Create("SourceRepositoryProvider", sourceRepositoryProvider); var solutionManagerTuple = Tuple.Create("VsSolutionManager", solutionManager); diff --git a/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetPackageSearchServiceTests.cs b/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetPackageSearchServiceTests.cs index d451a16b6e2..91370ebba7c 100644 --- a/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetPackageSearchServiceTests.cs +++ b/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetPackageSearchServiceTests.cs @@ -9,20 +9,18 @@ using System.Threading.Tasks; using Microsoft.ServiceHub.Framework; using Microsoft.ServiceHub.Framework.Services; -using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Sdk.TestFramework; using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NuGet.Common; using NuGet.Configuration; +using NuGet.PackageManagement.UI; using NuGet.Packaging.Core; -using NuGet.ProjectManagement; using NuGet.Protocol.Core.Types; -using NuGet.VisualStudio; +using NuGet.Versioning; using NuGet.VisualStudio.Internal.Contracts; using Test.Utility; using Xunit; @@ -37,7 +35,6 @@ public class NuGetPackageSearchServiceTests : MockedVSCollectionTests private readonly IEnumerable _installedPackages; private readonly IEnumerable _transitivePackages; private readonly IReadOnlyCollection _projects; - private readonly Mock _componentModel; public NuGetPackageSearchServiceTests(GlobalServiceProvider globalServiceProvider) : base(globalServiceProvider) @@ -62,8 +59,6 @@ public NuGetPackageSearchServiceTests(GlobalServiceProvider globalServiceProvide { "https://api.nuget.org/v3/registration3-gz-semver2/nuget.core/index.json", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.nugetCoreIndex.json", GetType()) }, { "https://api.nuget.org/v3/registration3-gz-semver2/microsoft.extensions.logging.abstractions/index.json", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.loggingAbstractions.json", GetType()) } }; - _componentModel = new Mock(); - globalServiceProvider.AddService(typeof(SComponentModel), _componentModel.Object); _sourceRepository = StaticHttpHandler.CreateSource(testFeedUrl, Repository.Provider.GetCoreV3(), responses); } @@ -296,15 +291,10 @@ private NuGetPackageSearchService SetupSearchService() var settings = new Mock(); var deleteOnRestartManager = new Mock(); - _componentModel.Setup(x => x.GetService()).Returns(deleteOnRestartManager.Object); - _componentModel.Setup(x => x.GetService()).Returns(solutionManager.Object); - _componentModel.Setup(x => x.GetService()).Returns(solutionManager.Object); - _componentModel.Setup(x => x.GetService()).Returns(settings.Object); - _componentModel.Setup(x => x.GetService()).Returns(sourceRepositoryProvider.Object); - _componentModel.Setup(x => x.GetService()).Returns(new Mock().Object); - - var service = Package.GetGlobalService(typeof(SAsyncServiceProvider)) as IAsyncServiceProvider; - ServiceLocator.InitializePackageServiceProvider(service); + AddService(Task.FromResult(deleteOnRestartManager.Object)); + AddService(Task.FromResult(solutionManager.Object)); + AddService(Task.FromResult(sourceRepositoryProvider.Object)); + AddService(Task.FromResult(settings.Object)); var serviceActivationOptions = default(ServiceActivationOptions); var serviceBroker = new Mock(); diff --git a/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetProjectManagerServiceTests.cs b/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetProjectManagerServiceTests.cs index f37d75fb660..e31f1d4ca24 100644 --- a/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetProjectManagerServiceTests.cs +++ b/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/NuGetProjectManagerServiceTests.cs @@ -11,7 +11,6 @@ using EnvDTE; using Microsoft.ServiceHub.Framework; using Microsoft.ServiceHub.Framework.Services; -using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.References; using Microsoft.VisualStudio.Sdk.TestFramework; @@ -57,9 +56,7 @@ public NuGetProjectManagerServiceTests(GlobalServiceProvider globalServiceProvid { _projectContext = new TestNuGetProjectContext(); - var componentModel = new Mock(); - componentModel.Setup(x => x.GetService()).Returns(_projectContext); - AddService(Task.FromResult((object)componentModel.Object)); + AddService(Task.FromResult(_projectContext)); } public void Dispose() diff --git a/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/SharedServiceStateTests.cs b/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/SharedServiceStateTests.cs index 57cb0b6d4df..bdeb6df5e4f 100644 --- a/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/SharedServiceStateTests.cs +++ b/test/NuGet.Clients.Tests/NuGet.PackageManagement.VisualStudio.Test/Services/SharedServiceStateTests.cs @@ -3,14 +3,10 @@ using System.Threading; using System.Threading.Tasks; -using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Sdk.TestFramework; -using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; using Moq; using NuGet.Configuration; using NuGet.Protocol.Core.Types; -using NuGet.VisualStudio; using Test.Utility; using Xunit; @@ -29,15 +25,10 @@ public SharedServiceStateTests(GlobalServiceProvider globalServiceProvider) SourceRepositoryProvider sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider(); - var componentModel = new Mock(); - componentModel.Setup(x => x.GetService()).Returns(Mock.Of()); - componentModel.Setup(x => x.GetService()).Returns(Mock.Of()); - componentModel.Setup(x => x.GetService()).Returns(sourceRepositoryProvider); - componentModel.Setup(x => x.GetService()).Returns(solutionManager.Object); - - globalServiceProvider.AddService(typeof(SComponentModel), componentModel.Object); - var service = Package.GetGlobalService(typeof(SAsyncServiceProvider)) as IAsyncServiceProvider; - ServiceLocator.InitializePackageServiceProvider(service); + AddService(Task.FromResult(Mock.Of())); + AddService(Task.FromResult(Mock.Of())); + AddService(Task.FromResult(sourceRepositoryProvider)); + AddService(Task.FromResult(solutionManager.Object)); } [Fact] diff --git a/test/NuGet.Clients.Tests/NuGet.Tools.Test/NuGetBrokeredServiceFactoryTests.cs b/test/NuGet.Clients.Tests/NuGet.Tools.Test/NuGetBrokeredServiceFactoryTests.cs index c85e5221c23..6a883c9e4ee 100644 --- a/test/NuGet.Clients.Tests/NuGet.Tools.Test/NuGetBrokeredServiceFactoryTests.cs +++ b/test/NuGet.Clients.Tests/NuGet.Tools.Test/NuGetBrokeredServiceFactoryTests.cs @@ -13,14 +13,11 @@ using Microsoft.ServiceHub.Framework.Services; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Sdk.TestFramework; -using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.ServiceBroker; using Moq; using NuGet.Configuration; using NuGet.PackageManagement.VisualStudio; using NuGet.Protocol.Core.Types; -using NuGet.VisualStudio; using NuGet.VisualStudio.Implementation.Extensibility; using NuGet.VisualStudio.Internal.Contracts; using NuGet.VisualStudio.Telemetry; @@ -46,20 +43,20 @@ public NuGetBrokeredServiceFactoryTests(GlobalServiceProvider globalServiceProvi var componentModel = new Mock(); var compositionService = new MockCompositionService(); + componentModel.SetupGet(x => x.DefaultCompositionService) + .Returns(compositionService); + var sourceRepositoryProvider = new Mock(); + sourceRepositoryProvider.SetupGet(x => x.PackageSourceProvider) .Returns(Mock.Of()); - componentModel.SetupGet(x => x.DefaultCompositionService) - .Returns(compositionService); - componentModel.Setup(x => x.GetService()).Returns(Mock.Of()); - componentModel.Setup(x => x.GetService()).Returns(Mock.Of()); - componentModel.Setup(x => x.GetService()).Returns(sourceRepositoryProvider.Object); - componentModel.Setup(x => x.GetService()).Returns(Mock.Of()); - + globalServiceProvider.AddService(typeof(IVsSolutionManager), Mock.Of()); + globalServiceProvider.AddService(typeof(ISettings), Mock.Of()); + globalServiceProvider.AddService(typeof(ISourceRepositoryProvider), sourceRepositoryProvider.Object); globalServiceProvider.AddService(typeof(SComponentModel), componentModel.Object); - var service = Package.GetGlobalService(typeof(SAsyncServiceProvider)) as IAsyncServiceProvider; - ServiceLocator.InitializePackageServiceProvider(service); + globalServiceProvider.AddService(typeof(INuGetTelemetryProvider), Mock.Of()); + _serviceFactories = new Dictionary(); _authorizingServiceFactories = new Dictionary(); }