// Copyright (C) 2025 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 using System; using System.Collections.Concurrent; using System.Threading.Tasks; using Microsoft.VisualStudio.Shell; namespace QtVsTools.VisualStudio { using ServiceType = Tuple; public interface IVsServiceProvider { I GetService() where T : class where I : class; Task GetServiceAsync() where T : class where I : class; } public static class VsServiceProvider { public static IVsServiceProvider Instance { get; set; } static readonly ConcurrentDictionary services = new(); public static I GetService() where I : class { return GetService(); } public static I GetService() where T : class where I : class { if (Instance == null) return null; if (services.TryGetValue(new ServiceType(typeof(T), typeof(I)), out object serviceObj)) return serviceObj as I; var serviceInterface = Instance.GetService(); services.TryAdd(new ServiceType(typeof(T), typeof(I)), serviceInterface); return serviceInterface; } public static async Task GetServiceAsync() where I : class { return await GetServiceAsync(); } public static async Task GetServiceAsync() where T : class where I : class { if (Instance == null) return null; if (services.TryGetValue(new ServiceType(typeof(T), typeof(I)), out object serviceObj)) return serviceObj as I; var serviceInterface = await Instance.GetServiceAsync(); services.TryAdd(new ServiceType(typeof(T), typeof(I)), serviceInterface); return serviceInterface; } public static I GetGlobalService() where T : class where I : class { return Package.GetGlobalService(typeof(T)) as I; } } }