Visual Studio 中的 NuGet API
除了 Visual Studio 中的 封裝管理員 UI 和 Console 之外,NuGet 也會導出其他延伸模組可以使用的一些實用服務。 這些介面可讓 Visual Studio 中的其他元件與 NuGet 互動,其可用來安裝和卸載套件,以及取得已安裝套件的相關信息。
NuGet 透過兩種不同的技術提供服務,每個技術都有其介面定義在不同的 NuGet 套件中。 NuGet 的較舊服務可透過 Managed Extensibility Framework (MEF)取得,其可在 NuGet.VisualStudio 套件中取得(移至 NuGet 的 MEF 服務)。 有一個較新的 API,設計為可與程式代碼搭配 async
使用,可在套件 NuGet.VisualStudio.Contracts
中使用 ,使用 Visual Studio 的 IServiceBroker
(移至 NuGet 的 Brokered Services)。
套件版本
NuGet 的產品遵循 Visual Studio 的版本,但落後 11.0 版。 例如,NuGet 6.0 會對應至 Visual Studio 2022 17.0、NuGet 5.11 對應至 Visual Studio 2019 16.11 等等。
從 Visual Studio 17.1 開始,NuGet 的 Visual Studio 擴充性 API 套件符合 API 的目標 Visual Studio 版本。 例如,當您的延伸模組以 Visual Studio 17.1 和更新版本為目標時,應該使用 NuGet.VisualStudio 和 NuGet.VisualStudio.Contracts 套件 17.1.0 版。 在 Visual Studio 17.0 和更早版本中,NuGet 的套件版本與 NuGet 的產品版本相同。 例如,如果您的延伸模組以 Visual Studio 2022 17.0 版為目標,您應該使用 NuGet 的 Visual Studio 擴充性套件 6.0 版。
Visual Studio 延伸模組中的 NuGet 用戶端 SDK
Visual Studio 擴充功能僅支援 和 NuGet.VisualStudio.Contracts
中的 NuGet.VisualStudio
API。
NuGet 會提供這些元件的系結重新導向,因此這些元件不需要包含在延伸模組中。
Visual Studio 延伸模組不支援使用 NuGet 用戶端 SDK 套件,例如 NuGet.Protocol
。
NuGet 不會提供這些元件的系結重新導向。
如需詳細資訊,請參閱 NuGet 用戶端 SDK 支持原則 。
服務清單
Brokered Services
這些服務可在套件 NuGet.VisualStudio.Contracts 中取得。
INuGetProjectService
:與項目互動的方法。 (5.7+)
MEF 服務
從 NuGet 6.0,這些 API 全都可在 NuGet.VisualStudio 套件中使用。 在 NuGet 5.11 和更早版本中,命名空間 NuGet.VisualStudio
中的 API 可在套件 NuGet.VisualStudio 中使用,而命名空間 NuGet.SolutionRestoreManager
中的 API 可在套件 NuGet.SolutionRestoreManager.Interop 中使用。
NuGet.VisualStudio
IRegistryKey
:從登錄子機碼值擷取值的方法。 (3.3+)IVsCredentialProvider
包含取得 NuGet 作業認證的方法。 (4.0+)IVsFrameworkCompatibility
包含探索架構與架構之間相容性的方法。 (4.0+)IVsFrameworkCompatibility2
包含探索架構與架構之間相容性的方法。 (4.0+)IVsFrameworkCompatibility3
包含探索架構與架構之間相容性的方法。 (5.8+)IVsFrameworkParser
用來處理字串與 FrameworkName 之間轉換的介面 (4.0+)IVsFrameworkParser2
剖析 .NET Framework 字串的介面。 請參閱 NuGet-IVsFrameworkParser。 (5.8+)IVsGlobalPackagesInitScriptExecutor
在解決方案中從 package(s) 執行 powershell 腳本(4.0+)IVsPackageInstaller
:將 NuGet 套件安裝到專案的方法。 (3.3+)- 'IVsPackageInstaller2 Contains 方法可將最新版本的單一套件安裝到目前方案內的專案中。
IVsPackageInstallerEvents
:套件安裝/解除安裝的事件。 (3.3+)IVsPackageInstallerProjectEvents
:套件安裝/解除安裝的批次事件。 (3.3+)IVsPackageInstallerServices
:在目前解決方案中擷取已安裝套件,以及檢查指定套件是否安裝在專案中的方法。 (3.3+)IVsPackageManagerProvider
:為 NuGet 套件提供替代之套件管理員建議的方法。 (3.3 - 5.11)IVsPackageRestorer
:還原專案中已安裝套件的方法。 (3.3+)IVsPackageSourceProvider
:擷取 NuGet 套件來源清單的方法。 (3.3+)IVsPackageUninstaller
:從專案解除安裝 NuGet 套件的方法。 (3.3+)IVsPathContext
目前內容特有的 NuGet 路徑資訊(例如項目內容)。 (4.0+)IVsPathContext2
目前內容特有的 NuGet 路徑資訊(例如項目內容)。 (5.0+)IVsPathContextProvider
初始化 IVsPathContext 實例的處理站。 (4.0+)IVsPathContextProvider2
初始化 IVsPathContext2 實例的處理站。 (5.0+)IVsProjectJsonToPackageReferenceMigrator
包含將project.json型舊版專案移轉至 PackageReference 型專案的方法。 (4.3+)IVsSemanticVersionComparer
將兩個不透明版本字串視為 NuGet 語意來比較兩個不透明的版本字串串的介面(4.0+)IVsNuGetProjectUpdateEvents
(6.2+)
NuGet.SolutionRestoreManager
這些介面是專為項目系統所設計,可與 NuGet 互動,讓專案系統通知 NuGet PackageReference
變更,並協調批次更新。 不是項目系統的Visual Studio延伸模組可能無法受益於這些 API。
IVsSolutionRestoreService
(4.0+)IVsSolutionRestoreService2
(4.3+)IVsSolutionRestoreService3
(5.1+)IVsSolutionRestoreService4
(6.0+)IVsSolutionRestoreStatusProvider
(6.0+)
使用 NuGet 服務
警告
除了程式代碼中的公用介面之外,請勿使用任何其他類型,也不會參考任何其他 NuGet 元件,例如 NuGet.Protocol.dll
、 NuGet.Frameworks.dll
等等。
為了將我們所做的回溯相容性承諾最大化,但也可讓您彈性地在 Visual Studio 中實作新功能、效能改善和 Bug 修正,我們不支援 Visual Studio 中使用的 NuGet 用戶端 SDK,而且我們不會在 VS 擴充性合約以外的元件中提供系結 devenv.exe.config
重新導向。
如果您想要在 Visual Studio 中建立新的 NuGet 相關 API,請搜尋 NuGet 的主存放庫 ,並在找到類似的問題時提出任何現有問題。 如果您找不到現有功能要求來啟動,請建立一個。
Brokered Services
將
NuGet.VisualStudio.Contracts
套件安裝到您的專案,以及Microsoft.VisualStudio.SDK
。IAsyncServiceProvider
使用 來取得 Visual Studio 的服務代理人,並使用該代理程式來取得 NuGet 的服務。 請注意,AsyncPackage
會IVsAsyncServiceProvider2
擴充 ,讓實作 的AsyncPackage
類別可以做為IAsyncServiceProvider
。 另請參閱和 上的檔IBrokeredServiceContainer
IServiceBroker
// Your AsyncPackage implements IAsyncServiceProvider IAsyncServiceProvider asyncServiceProvider = this; var brokeredServiceContainer = await asyncServiceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>(); var serviceBroker = brokeredServiceContainer.GetFullAccessServiceBroker(); var nugetProjectService = await serviceBroker.GetProxyAsync<INuGetProjectService>(NuGetServices.NuGetProjectServiceV1);
當您的程式代碼不再需要 NuGet 的代理服務時,請處置它。 例如,如果您在單一方法呼叫期間只需要 NuGet 的代理服務,您可以將它包裝在 C#
using
語句中:InstalledPackagesResult installedPackagesResult; using (nugetProjectService as IDisposable) { installedPackagesResult = await nugetProjectService.GetInstalledPackages(projectGuid, cancellationToken); }
MEF 服務
將
NuGet.VisualStudio
套件安裝到您的專案,其中包含NuGet.VisualStudio.dll
組件。在 NuGet 5.11 和更早版本中,套件會自動將元件參考的 Embed Interop Types 屬性設定為 True。 關於內嵌 Interop 類型的 Visual Studio 2022 原則已變更,因此 NuGet.VisualStudio 套件 6.0.0 版和更新版本不再使用此原則。
若要使用服務,請透過 MEF 匯入屬性匯入它,或透過 IComponentModel 服務。
//Using the Import attribute [Import(typeof(IVsPackageInstaller2))] public IVsPackageInstaller2 packageInstaller; packageInstaller.InstallLatestPackage(null, currentProject, "Newtonsoft.Json", false, false); //Using the IComponentModel service var componentModel = (IComponentModel)GetService(typeof(SComponentModel)); IVsPackageInstallerServices installerServices = componentModel.GetService<IVsPackageInstallerServices>(); var installedPackages = installerServices.GetInstalledPackages();
NuGet.VisualStudio 原始程式碼包含在 NuGet.Clients 儲存機制 內,供您參考。
瞭解 .NET 項目系統
為 .NET Core 1.0 新增 SDK 樣式專案時,其設計目的是比先前的 Visual Studio 專案系統更異步。 這會影響所有其他 Visual Studio 元件與其直接互動的方式,或 NuGet 等其他元件。 這是最明顯的解決方案載入和專案載入,其中專案在Visual Studio的舊版同步 API 通知已引發之後一段時間未完全可用。
在方案載入期間,NuGet 會 IVsSolutionEvents.OnAfterProjectLoad
忽略 ,以避免延遲解決方案載入的同步部分。 NuGet 會在解決方案載入的同步部分完成之後,同步處理其內部數據結構。 這也適用於非 SDK 樣式專案。
即使所有 IVsSolutionEvents.OnAfterSolutionLoad
事件處理程式都完成,這隻會發出解決方案載入同步部分的結尾。 解決方案載入的異步部分仍在進行中。 因此,如果您的擴充功能在專案或InstallPackage
方案載入之後呼叫NuGet API,NuGet GetInstalledPackagesAsync
可能會擲回InvalidOperationException
類似「無法載入專案 {專案名稱} 的詳細數據,作業失敗」的訊息。
當方案包含至少一個 SDK 樣式專案時,NuGet 會在方案載入後自動執行還原,而且在完成之前,您不應該呼叫任何 Nuget API。 您可以在解決方案還原或特定專案還原完成時,使用 IVsNuGetProjectUpdateEvents
來取得通知。 如果方案未包含任何 SDK 樣式專案,則還原將不會自動排程,而且在排程組建之前可能不會發生。
若要判斷專案是否使用 NuGet 的異步流程 (SDK 樣式專案),請使用 PackageUtilities.IsCapabilityMatch
表示式 CPS + PackageReference
。
INuGetProjectService 介面
/// <summary>Service to interact with projects in a solution</summary>
/// <remarks>This interface should not be implemented. New methods may be added over time.</remarks>
public interface INuGetProjectService
{
/// <Summary>Gets the list of packages installed in a project.</Summary>
/// <param name="projectId">Project ID (GUID).</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The list of packages in the project.</returns>
Task<InstalledPackagesResult> GetInstalledPackagesAsync(Guid projectId, CancellationToken cancellationToken);
}
IRegistryKey 介面
/// <summary>
/// Specifies methods for manipulating a key in the Windows registry.
/// </summary>
public interface IRegistryKey
{
/// <summary>
/// Retrieves the specified subkey for read or read/write access.
/// </summary>
/// <param name="name">The name or path of the subkey to create or open.</param>
/// <returns>The subkey requested, or null if the operation failed.</returns>
IRegistryKey OpenSubKey(string name);
/// <summary>
/// Retrieves the value associated with the specified name.
/// </summary>
/// <param name="name">The name of the value to retrieve. This string is not case-sensitive.</param>
/// <returns>The value associated with name, or null if name is not found.</returns>
object GetValue(string name);
/// <summary>
/// Closes the key and flushes it to disk if its contents have been modified.
/// </summary>
void Close();
}
IVsCredentialProvider 介面
/// <summary>
/// Contains methods to get credentials for NuGet operations.
/// </summary>
public interface IVsCredentialProvider
{
/// <summary>
/// Get credentials for the supplied package source Uri.
/// </summary>
/// <param name="uri">The NuGet package source Uri for which credentials are being requested. Implementors are
/// expected to first determine if this is a package source for which they can supply credentials.
/// If not, then Null should be returned.</param>
/// <param name="proxy">Web proxy to use when comunicating on the network. Null if there is no proxy
/// authentication configured.</param>
/// <param name="isProxyRequest">True if if this request is to get proxy authentication
/// credentials. If the implementation is not valid for acquiring proxy credentials, then
/// null should be returned.</param>
/// <param name="isRetry">True if credentials were previously acquired for this uri, but
/// the supplied credentials did not allow authorized access.</param>
/// <param name="nonInteractive">If true, then interactive prompts must not be allowed.</param>
/// <param name="cancellationToken">This cancellation token should be checked to determine if the
/// operation requesting credentials has been cancelled.</param>
/// <returns>Credentials acquired by this provider for the given package source uri.
/// If the provider does not handle requests for the input parameter set, then null should be returned.
/// If the provider does handle the request, but cannot supply credentials, an exception should be thrown.</returns>
Task<ICredentials> GetCredentialsAsync(Uri uri,
IWebProxy proxy,
bool isProxyRequest,
bool isRetry,
bool nonInteractive,
CancellationToken cancellationToken);
}
IVsFrameworkCompatibility 介面
/// <summary>
/// Contains methods to discover frameworks and compatibility between frameworks.
/// </summary>
public interface IVsFrameworkCompatibility
{
/// <summary>
/// Gets all .NETStandard frameworks currently supported, in ascending order by version.
/// </summary>
/// <remarks>This API is <a href="https://github.com/microsoft/vs-threading/blob/main/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded.</a></remarks>
IEnumerable<FrameworkName> GetNetStandardFrameworks();
/// <summary>
/// Gets frameworks that support packages of the provided .NETStandard version.
/// </summary>
/// <remarks>
/// The result list is not exhaustive as it is meant to human-readable. For example,
/// equivalent frameworks are not returned. Additionally, a framework name with version X
/// in the result implies that framework names with versions greater than or equal to X
/// but having the same <see cref="FrameworkName.Identifier"/> are also supported.
///
/// <para>This API is <a href="https://github.com/microsoft/vs-threading/blob/main/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded.</a></para>
/// </remarks>
/// <param name="frameworkName">The .NETStandard version to get supporting frameworks for.</param>
[Obsolete("This API does not support .NET 5 and higher target frameworks with platforms. Use IVsFrameworkCompatibility3 instead.")]
IEnumerable<FrameworkName> GetFrameworksSupportingNetStandard(FrameworkName frameworkName);
/// <summary>
/// Selects the framework from <paramref name="frameworks"/> that is nearest
/// to the <paramref name="targetFramework"/>, according to NuGet's framework
/// compatibility rules. <c>null</c> is returned of none of the frameworks
/// are compatible.
/// </summary>
/// <remarks>This API is <a href="https://github.com/microsoft/vs-threading/blob/main/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded.</a></remarks>
/// <param name="targetFramework">The target framework.</param>
/// <param name="frameworks">The list of frameworks to choose from.</param>
/// <exception cref="ArgumentException">If any of the arguments are <c>null</c>.</exception>
/// <returns>The nearest framework.</returns>
[Obsolete("This API does not support .NET 5 and higher target frameworks with platforms. Use IVsFrameworkCompatibility3 instead.")]
FrameworkName GetNearest(FrameworkName targetFramework, IEnumerable<FrameworkName> frameworks);
}
IVsFrameworkCompatibility2 介面
/// <summary>
/// Contains methods to discover frameworks and compatibility between frameworks.
/// </summary>
[Obsolete("This API does not support .NET 5 and higher target frameworks with platforms. Use IVsFrameworkCompatibility3 instead.")]
public interface IVsFrameworkCompatibility2 : IVsFrameworkCompatibility
{
/// <summary>
/// Selects the framework from <paramref name="frameworks"/> that is nearest
/// to the <paramref name="targetFramework"/>, according to NuGet's framework
/// compatibility rules. <c>null</c> is returned of none of the frameworks
/// are compatible.
/// </summary>
/// <remarks>This API is <a href="https://github.com/microsoft/vs-threading/blob/main/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded.</a></remarks>
/// <param name="targetFramework">The target framework.</param>
/// <param name="fallbackTargetFrameworks">
/// Target frameworks to use if the provided <paramref name="targetFramework"/> is not compatible.
/// These fallback frameworks are attempted in sequence after <paramref name="targetFramework"/>.
/// </param>
/// <param name="frameworks">The list of frameworks to choose from.</param>
/// <exception cref="ArgumentException">If any of the arguments are <c>null</c>.</exception>
/// <returns>The nearest framework.</returns>
[Obsolete("This API does not support .NET 5 and higher target frameworks with platforms. Use IVsFrameworkCompatibility3 instead.")]
FrameworkName GetNearest(
FrameworkName targetFramework,
IEnumerable<FrameworkName> fallbackTargetFrameworks,
IEnumerable<FrameworkName> frameworks);
}
IVsFrameworkCompatibility3 介面
/// <summary>
/// Contains methods to discover frameworks and compatibility between frameworks.
/// </summary>
public interface IVsFrameworkCompatibility3
{
/// <summary>
/// Selects the framework from <paramref name="frameworks"/> that is nearest
/// to the <paramref name="targetFramework"/>, according to NuGet's framework
/// compatibility rules. <c>null</c> is returned of none of the frameworks
/// are compatible.
/// </summary>
/// <param name="targetFramework">The target framework.</param>
/// <param name="frameworks">The list of frameworks to choose from.</param>
/// <exception cref="ArgumentNullException">If any of the arguments are null.</exception>
/// <exception cref="ArgumentException">If any of the frameworks cannot be parsed.</exception>
/// <returns>The nearest framework.</returns>
/// <remarks>This API is <a href="https://github.com/microsoft/vs-threading/blob/9f065f155525c4561257e02ad61e66e93e073886/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded</a>.</remarks>
IVsNuGetFramework GetNearest(IVsNuGetFramework targetFramework, IEnumerable<IVsNuGetFramework> frameworks);
/// <summary>
/// Selects the framework from <paramref name="frameworks"/> that is nearest
/// to the <paramref name="targetFramework"/>, according to NuGet's framework
/// compatibility rules. <c>null</c> is returned of none of the frameworks
/// are compatible.
/// </summary>
/// <param name="targetFramework">The target framework.</param>
/// <param name="fallbackTargetFrameworks">
/// Target frameworks to use if the provided <paramref name="targetFramework"/> is not compatible.
/// These fallback frameworks are attempted in sequence after <paramref name="targetFramework"/>.
/// </param>
/// <param name="frameworks">The list of frameworks to choose from.</param>
/// <exception cref="ArgumentNullException">If any of the arguments are null.</exception>
/// <exception cref="ArgumentException">If any of the frameworkscannot be parsed.</exception>
/// <returns>The nearest framework.</returns>
/// <remarks>This API is <a href="https://github.com/microsoft/vs-threading/blob/9f065f155525c4561257e02ad61e66e93e073886/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded</a>.</remarks>
IVsNuGetFramework GetNearest(
IVsNuGetFramework targetFramework,
IEnumerable<IVsNuGetFramework> fallbackTargetFrameworks,
IEnumerable<IVsNuGetFramework> frameworks);
}
IVsFrameworkParser 介面
/// <summary>
/// An interface for dealing with the conversion between strings and <see cref="FrameworkName"/>
/// instances.
/// </summary>
[Obsolete("This API does not support .NET 5 and higher target frameworks with platforms. Use IVsFrameworkParser2 instead.")]
public interface IVsFrameworkParser
{
/// <summary>
/// Parses a short framework name (e.g. "net45") or a full framework name
/// (e.g. ".NETFramework,Version=v4.5") into a <see cref="FrameworkName"/>
/// instance.
/// </summary>
/// <remarks>This API is <a href="https://github.com/microsoft/vs-threading/blob/main/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded.</a></remarks>
/// <param name="shortOrFullName">The framework string.</param>
/// <exception cref="ArgumentNullException">If the provided string is null.</exception>
/// <exception cref="ArgumentException">If the provided string cannot be parsed.</exception>
/// <returns>The parsed framework.</returns>
[Obsolete("This API does not support .NET 5 and higher target frameworks with platforms. Use IVsFrameworkParser2 instead.")]
FrameworkName ParseFrameworkName(string shortOrFullName);
/// <summary>
/// Gets the shortened version of the framework name from a <see cref="FrameworkName"/>
/// instance.
/// </summary>
/// <remarks>
/// For example, ".NETFramework,Version=v4.5" is converted to "net45". This is the value
/// used inside of .nupkg folder structures as well as in project.json files.
/// <para>This API is <a href="https://github.com/microsoft/vs-threading/blob/main/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded.</a></para>
/// </remarks>
/// <param name="frameworkName">The framework name.</param>
/// <exception cref="ArgumentNullException">If the input is null.</exception>
/// <exception cref="ArgumentException">
/// If the provided framework name cannot be converted to a short name.
/// </exception>
/// <returns>The short framework name. </returns>
[Obsolete("This API does not support .NET 5 and higher target frameworks with platforms. Use IVsFrameworkParser2 instead.")]
string GetShortFrameworkName(FrameworkName frameworkName);
}
IVsFrameworkParser2 介面
/// <summary>An interface to parse .NET Framework strings. See <a href="http://aka.ms/NuGet-IVsFrameworkParser">http://aka.ms/NuGet-IVsFrameworkParser</a>.</summary>
public interface IVsFrameworkParser2
{
/// <summary>
/// Parses a short framework name (e.g. "net45") or a full Target Framework Moniker
/// (e.g. ".NETFramework,Version=v4.5") into a <see cref="IVsNuGetFramework"/>
/// instance.
/// </summary>
/// <param name="input">The framework string</param>
/// <param name="nuGetFramework">The resulting <see cref="IVsNuGetFramework"/>. If the method returns false, this return NuGet's "Unsupported" framework details.</param>
/// <returns>A boolean to specify whether the input could be parsed into a valid <see cref="IVsNuGetFramework"/> object.</returns>
/// <remarks>This API is not needed to get framework information about loaded projects, and should not be used to parse the project's TargetFramework property. See <a href="http://aka.ms/NuGet-IVsFrameworkParser">http://aka.ms/NuGet-IVsFrameworkParser</a>.<br/>
/// This API is <a href="https://github.com/microsoft/vs-threading/blob/9f065f155525c4561257e02ad61e66e93e073886/doc/cookbook_vs.md#how-do-i-effectively-verify-that-my-code-is-fully-free-threaded">free-threaded</a>.</remarks>
bool TryParse(string input, out IVsNuGetFramework nuGetFramework);
}
IVsGlobalPackagesInitScriptExecutor 介面
/// <summary>
/// Execute powershell scripts from package(s) in a solution
/// </summary>
/// <remarks>Intended for internal use only.</remarks>
public interface IVsGlobalPackagesInitScriptExecutor
{
/// <summary>
/// Executes the init script of the given package if available.
/// 1) If the init.ps1 script has already been executed by the powershell host, it will not be executed again.
/// True is returned.
/// 2) If the package is found in the global packages folder it will be used.
/// If not, it will return false and do nothing.
/// 3) Also, note if other scripts are executing while this call was made, it will wait for them to complete.
/// </summary>
/// <param name="packageId">Id of the package whose init.ps1 will be executed.</param>
/// <param name="packageVersion">Version of the package whose init.ps1 will be executed.</param>
/// <returns>Returns true if the script was executed or has been executed already.</returns>
/// <remarks>This method throws if the init.ps1 being executed throws.</remarks>
Task<bool> ExecuteInitScriptAsync(string packageId, string packageVersion);
}
IVsPackageInstaller 介面
/// <summary>
/// Contains methods to install packages into a project within the current solution.
/// </summary>
[ComImport]
[Guid("4F3B122B-A53B-432C-8D85-0FAFB8BE4FF4")]
public interface IVsPackageInstaller
{
/// <summary>
/// Installs a single package from the specified package source.
/// </summary>
/// <remarks>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></remarks>
/// <param name="source">
/// The package source to install the package from. This value can be <c>null</c>
/// to indicate that the user's configured sources should be used. Otherwise,
/// this should be the source path as a string. If the user has credentials
/// configured for a source, this value must exactly match the configured source
/// value.
/// </param>
/// <param name="project">The target project for package installation.</param>
/// <param name="packageId">The package ID of the package to install.</param>
/// <param name="version">
/// The version of the package to install. <c>null</c> can be provided to
/// install the latest version of the package.
/// </param>
/// <param name="ignoreDependencies">
/// A boolean indicating whether or not to ignore the package's dependencies
/// during installation.
/// </param>
[Obsolete("System.Version does not support SemVer pre-release versions. Use the overload with string version instead.")]
void InstallPackage(string source, Project project, string packageId, Version version, bool ignoreDependencies);
/// <summary>
/// Installs a single package from the specified package source.
/// </summary>
/// <remarks>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></remarks>
/// <param name="source">
/// The package source to install the package from. This value can be <c>null</c>
/// to indicate that the user's configured sources should be used. Otherwise,
/// this should be the source path as a string. If the user has credentials
/// configured for a source, this value must exactly match the configured source
/// value.
/// </param>
/// <param name="project">The target project for package installation.</param>
/// <param name="packageId">The package ID of the package to install.</param>
/// <param name="version">
/// The version of the package to install. <c>null</c> can be provided to
/// install the latest version of the package.
/// </param>
/// <param name="ignoreDependencies">
/// A boolean indicating whether or not to ignore the package's dependencies
/// during installation.
/// </param>
void InstallPackage(string source, Project project, string packageId, string version, bool ignoreDependencies);
/// <summary>
/// Installs a single package from the specified package source.
/// </summary>
/// <param name="repository">The package repository to install the package from.</param>
/// <param name="project">The target project for package installation.</param>
/// <param name="packageId">The package id of the package to install.</param>
/// <param name="version">
/// The version of the package to install. <c>null</c> can be provided to
/// install the latest version of the package.
/// </param>
/// <param name="ignoreDependencies">
/// A boolean indicating whether or not to ignore the package's dependencies
/// during installation.
/// </param>
/// <param name="skipAssemblyReferences">
/// A boolean indicating if assembly references from the package should be
/// skipped.
/// </param>
[Obsolete]
void InstallPackage(IPackageRepository repository, Project project, string packageId, string version, bool ignoreDependencies, bool skipAssemblyReferences);
/// <summary>
/// Installs one or more packages that exist on disk in a folder defined in the registry.
/// </summary>
/// <param name="keyName">
/// The registry key name (under NuGet's repository key) that defines the folder on disk
/// containing the packages.
/// </param>
/// <param name="isPreUnzipped">
/// A boolean indicating whether the folder contains packages that are
/// pre-unzipped.
/// </param>
/// <param name="skipAssemblyReferences">
/// A boolean indicating whether the assembly references from the packages
/// should be skipped.
/// </param>
/// <param name="project">The target project for package installation.</param>
/// <param name="packageVersions">
/// A dictionary of packages/versions to install where the key is the package id
/// and the value is the version.
/// </param>
/// <remarks>
/// If any version of the package is already installed, no action will be taken.
/// <para>
/// Dependencies are always ignored.
/// </para>
/// <para>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></para>
/// </remarks>
void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, Project project, IDictionary<string, string> packageVersions);
/// <summary>
/// Installs one or more packages that exist on disk in a folder defined in the registry.
/// </summary>
/// <param name="keyName">
/// The registry key name (under NuGet's repository key) that defines the folder on disk
/// containing the packages.
/// </param>
/// <param name="isPreUnzipped">
/// A boolean indicating whether the folder contains packages that are
/// pre-unzipped.
/// </param>
/// <param name="skipAssemblyReferences">
/// A boolean indicating whether the assembly references from the packages
/// should be skipped.
/// </param>
/// <param name="ignoreDependencies">A boolean indicating whether the package's dependencies should be ignored</param>
/// <param name="project">The target project for package installation.</param>
/// <param name="packageVersions">
/// A dictionary of packages/versions to install where the key is the package id
/// and the value is the version.
/// </param>
/// <remarks>
/// If any version of the package is already installed, no action will be taken.
/// <para>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></para>
/// </remarks>
void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary<string, string> packageVersions);
/// <summary>
/// Installs one or more packages that are embedded in a Visual Studio Extension Package.
/// </summary>
/// <param name="extensionId">The Id of the Visual Studio Extension Package.</param>
/// <param name="isPreUnzipped">
/// A boolean indicating whether the folder contains packages that are
/// pre-unzipped.
/// </param>
/// <param name="skipAssemblyReferences">
/// A boolean indicating whether the assembly references from the packages
/// should be skipped.
/// </param>
/// <param name="project">The target project for package installation</param>
/// <param name="packageVersions">
/// A dictionary of packages/versions to install where the key is the package id
/// and the value is the version.
/// </param>
/// <remarks>
/// If any version of the package is already installed, no action will be taken.
/// <para>
/// Dependencies are always ignored.
/// </para>
/// <para>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></para>
/// </remarks>
void InstallPackagesFromVSExtensionRepository(string extensionId, bool isPreUnzipped, bool skipAssemblyReferences, Project project, IDictionary<string, string> packageVersions);
/// <summary>
/// Installs one or more packages that are embedded in a Visual Studio Extension Package.
/// </summary>
/// <param name="extensionId">The Id of the Visual Studio Extension Package.</param>
/// <param name="isPreUnzipped">
/// A boolean indicating whether the folder contains packages that are
/// pre-unzipped.
/// </param>
/// <param name="skipAssemblyReferences">
/// A boolean indicating whether the assembly references from the packages
/// should be skipped.
/// </param>
/// <param name="ignoreDependencies">A boolean indicating whether the package's dependencies should be ignored</param>
/// <param name="project">The target project for package installation</param>
/// <param name="packageVersions">
/// A dictionary of packages/versions to install where the key is the package id
/// and the value is the version.
/// </param>
/// <remarks>
/// If any version of the package is already installed, no action will be taken.
/// <para>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></para>
/// </remarks>
void InstallPackagesFromVSExtensionRepository(string extensionId, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary<string, string> packageVersions);
}
IVsPackageinstaller2 介面
/// <summary>
/// Contains method to install latest version of a single package into a project within the current solution.
/// </summary>
public interface IVsPackageInstaller2 : IVsPackageInstaller
{
/// <summary>
/// Installs the latest version of a single package from the specified package source.
/// </summary>
/// <remarks>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></remarks>
/// <param name="source">
/// The package source to install the package from. This value can be <c>null</c>
/// to indicate that the user's configured sources should be used. Otherwise,
/// this should be the source path as a string. If the user has credentials
/// configured for a source, this value must exactly match the configured source
/// value.
/// </param>
/// <param name="project">The target project for package installation.</param>
/// <param name="packageId">The package ID of the package to install.</param>
/// <param name="includePrerelease">
/// Whether or not to consider prerelease versions when finding the latest version
/// to install.
/// </param>
/// <param name="ignoreDependencies">
/// A boolean indicating whether or not to ignore the package's dependencies
/// during installation.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown when <see paramref="includePrerelease"/> is <c>false</c> and no stable version
/// of the package exists.
/// </exception>
void InstallLatestPackage(
string source,
Project project,
string packageId,
bool includePrerelease,
bool ignoreDependencies);
}
IVsPackageInstallerEvents 介面
注意
這些事件只會針對 packages.config 項目引發。 若要取得 packages.config 和 PackageReference 的更新,請改用 IVsNuGetProjectUpdateEvents
。
/// <summary>
/// Contains events which are raised when packages are installed or uninstalled from projects and the current
/// solution.
/// </summary>
public interface IVsPackageInstallerEvents
{
/// <summary>
/// Raised when a package is about to be installed into the current solution.
/// </summary>
event VsPackageEventHandler PackageInstalling;
/// <summary>
/// Raised after a package has been installed into the current solution.
/// </summary>
event VsPackageEventHandler PackageInstalled;
/// <summary>
/// Raised when a package is about to be uninstalled from the current solution.
/// </summary>
event VsPackageEventHandler PackageUninstalling;
/// <summary>
/// Raised after a package has been uninstalled from the current solution.
/// </summary>
event VsPackageEventHandler PackageUninstalled;
/// <summary>
/// Raised after a package has been installed into a project within the current solution.
/// </summary>
event VsPackageEventHandler PackageReferenceAdded;
/// <summary>
/// Raised after a package has been uninstalled from a project within the current solution.
/// </summary>
event VsPackageEventHandler PackageReferenceRemoved;
}
IVsPackageInstallerProjectEvents 介面
注意
這些事件只會針對 packages.config 項目引發。 若要取得 packages.config 和 PackageReference 的更新,請改用 IVsNuGetProjectUpdateEvents
。
/// <summary>
/// Contains batch events which are raised when packages are installed or uninstalled from projects with packages.config
/// and the current solution.
/// </summary>
public interface IVsPackageInstallerProjectEvents
{
/// <summary>
/// Raised before any IVsPackageInstallerEvents events are raised for a project.
/// </summary>
event VsPackageProjectEventHandler BatchStart;
/// <summary>
/// Raised after all IVsPackageInstallerEvents events are raised for a project.
/// </summary>
event VsPackageProjectEventHandler BatchEnd;
}
IVsPackageInstallerServices 介面
/// <summary>
/// Contains methods to query for installed packages within the current solution.
/// </summary>
[Obsolete("Use INuGetProjectService in the NuGet.VisualStudio.Contracts package instead.")]
public interface IVsPackageInstallerServices
{
/// <summary>
/// Get the list of NuGet packages installed in the current solution.
/// </summary>
[Obsolete("This method can cause UI delays if called on the UI thread. Use INuGetProjectService.GetInstalledPackagesAsync in the NuGet.VisualStudio.Contracts package instead, and iterate all projects in the solution")]
IEnumerable<IVsPackageMetadata> GetInstalledPackages();
/// <summary>
/// Checks if a NuGet package with the specified Id is installed in the specified project.
/// </summary>
/// <param name="project">The project to check for NuGet package.</param>
/// <param name="id">The id of the package to check.</param>
/// <returns><c>true</c> if the package is install. <c>false</c> otherwise.</returns>
/// <exception cref="InvalidOperationException">A "project not nominated" exception will be thrown if the project system has not yet told NuGet about the project.
/// You can use <see cref="IVsNuGetProjectUpdateEvents"/> or Microsoft.VisualStudio.OperationProgress to be notified when the project is ready.</exception>
[Obsolete("This method can cause UI delays if called on the UI thread. Use INuGetProjectService.GetInstalledPackagesAsync in the NuGet.VisualStudio.Contracts package instead, and check the specific package you're interested in")]
bool IsPackageInstalled(Project project, string id);
/// <summary>
/// Checks if a NuGet package with the specified Id and version is installed in the specified project.
/// </summary>
/// <param name="project">The project to check for NuGet package.</param>
/// <param name="id">The id of the package to check.</param>
/// <param name="version">The version of the package to check.</param>
/// <returns><c>true</c> if the package is install. <c>false</c> otherwise.</returns>
/// <exception cref="InvalidOperationException">A "project not nominated" exception will be thrown if the project system has not yet told NuGet about the project.
/// You can use <see cref="IVsNuGetProjectUpdateEvents"/> or Microsoft.VisualStudio.OperationProgress to be notified when the project is ready.</exception>
[Obsolete("This method can cause UI delays if called on the UI thread. Use INuGetProjectService.GetInstalledPackagesAsync in the NuGet.VisualStudio.Contracts package instead, and check the specific package you're interested in")]
bool IsPackageInstalled(Project project, string id, SemanticVersion version);
/// <summary>
/// Checks if a NuGet package with the specified Id and version is installed in the specified project.
/// </summary>
/// <param name="project">The project to check for NuGet package.</param>
/// <param name="id">The id of the package to check.</param>
/// <param name="versionString">The version of the package to check.</param>
/// <returns><c>true</c> if the package is install. <c>false</c> otherwise.</returns>
/// <remarks>
/// The reason this method is named IsPackageInstalledEx, instead of IsPackageInstalled, is that
/// when client project compiles against this assembly, the compiler would attempt to bind against
/// the other overload which accepts SemanticVersion and would require client project to reference NuGet.Core.
/// </remarks>
/// <exception cref="InvalidOperationException">A "project not nominated" exception will be thrown if the project system has not yet told NuGet about the project.
/// You can use <see cref="IVsNuGetProjectUpdateEvents"/> or Microsoft.VisualStudio.OperationProgress to be notified when the project is ready.</exception>
[Obsolete("This method can cause UI delays if called on the UI thread. Use INuGetProjectService.GetInstalledPackagesAsync in the NuGet.VisualStudio.Contracts package instead, and check the specific package you're interested in")]
bool IsPackageInstalledEx(Project project, string id, string versionString);
/// <summary>
/// Get the list of NuGet packages installed in the specified project.
/// </summary>
/// <param name="project">The project to get NuGet packages from.</param>
/// <exception cref="InvalidOperationException">A "project not nominated" exception will be thrown if the project system has not yet told NuGet about the project.
/// You can use <see cref="IVsNuGetProjectUpdateEvents"/> or Microsoft.VisualStudio.OperationProgress to be notified when the project is ready.</exception>
[Obsolete("This method can cause UI delays if called on the UI thread. Use INuGetProjectService.GetInstalledPackagesAsync in the NuGet.VisualStudio.Contracts package instead")]
IEnumerable<IVsPackageMetadata> GetInstalledPackages(Project project);
}
IVsPackageManagerProvider 介面
此介面主要供 ASP.NET 小組使用,以建議和 之類的 jQuery
bootstrap
Javascript 和 CSS 套件會與 Bower 一起安裝,而不是 NuGet。 由於已從 Visual Studio 移除該功能,NuGet 已淘汰此介面,而且 Visual Studio 2022(17.0 版)和更新版本中的 封裝管理員 UI 將不再使用此功能。
/// <summary>
/// Interface allowing integration of alternate package manager suggestion for a NuGet package.
/// For example jQuery may appear on Bower and npm,
/// it might be more appropriate to install a package from them for certain projects.
/// </summary>
[Obsolete]
public interface IVsPackageManagerProvider
{
/// <summary>
/// Localized display package manager name.
/// </summary>
string PackageManagerName { get; }
/// <summary>
/// Package manager unique id.
/// </summary>
string PackageManagerId { get; }
/// <summary>
/// The tool tip description for the package
/// </summary>
string Description { get; }
/// <summary>
/// Check if a recommendation should be surfaced for an alternate package manager.
/// This code should not rely on slow network calls, and should return rapidly.
/// </summary>
/// <param name="packageId">Current package id</param>
/// <param name="projectName">Unique project name for finding the project through VS dte</param>
/// <param name="token">Cancellation Token</param>
/// <returns>return true if need to direct to integrated package manager for this package</returns>
Task<bool> CheckForPackageAsync(string packageId, string projectName, CancellationToken token);
/// <summary>
/// This Action should take the user to the other package manager.
/// </summary>
/// <param name="packageId">Current package id</param>
/// <param name="projectName">Unique project name for finding the project through VS dte</param>
void GoToPackage(string packageId, string projectName);
}
IVsPackageRestorer 介面
/// <summary>
/// Contains methods to restore packages installed in a project within the current solution.
/// </summary>
public interface IVsPackageRestorer
{
/// <summary>
/// Returns a value indicating whether the user consent to download NuGet packages
/// has been granted.
/// </summary>
/// <remarks>Can be called from a background thread.</remarks>
/// <returns>true if the user consent has been granted; otherwise, false.</returns>
bool IsUserConsentGranted();
/// <summary>
/// Restores NuGet packages installed in the given project within the current solution.
/// </summary>
/// <remarks>Can be called from a background thread.</remarks>
/// <param name="project">The project whose NuGet packages to restore.</param>
void RestorePackages(Project project);
}
IVsPackageSourceProvider 介面
/// <summary>
/// A public API for retrieving the list of NuGet package sources.
/// </summary>
public interface IVsPackageSourceProvider
{
/// <summary>
/// Provides the list of package sources.
/// </summary>
/// <remarks>Can be called from a background thread.</remarks>
/// <param name="includeUnOfficial">Unofficial sources will be included in the results</param>
/// <param name="includeDisabled">Disabled sources will be included in the results</param>
/// <remarks>Does not require the UI thread.</remarks>
/// <exception cref="ArgumentException">Thrown if a NuGet configuration file is invalid.</exception>
/// <exception cref="ArgumentNullException">Thrown if a NuGet configuration file is invalid.</exception>
/// <exception cref="InvalidOperationException">Thrown if a NuGet configuration file is invalid.</exception>
/// <exception cref="InvalidDataException">Thrown if a NuGet configuration file is invalid.</exception>
/// <returns>Key: source name Value: source URI</returns>
IEnumerable<KeyValuePair<string, string>> GetSources(bool includeUnOfficial, bool includeDisabled);
/// <summary>
/// Raised when sources are added, removed, disabled, or modified.
/// </summary>
event EventHandler SourcesChanged;
}
IVsPackageUninstaller 介面
/// <summary>
/// Contains methods to uninstall packages from a project within the current solution.
/// </summary>
public interface IVsPackageUninstaller
{
/// <summary>
/// Uninstall the specified package from a project and specify whether to uninstall its dependency packages
/// too.
/// </summary>
/// <remarks>Can be called from a background thread, if the UI thread is not blocked waiting for this to finish.
/// See <a href="https://github.com/nuget/home/issues/11476">https://github.com/nuget/home/issues/11476</a></remarks>
/// <param name="project">The project from which the package is uninstalled.</param>
/// <param name="packageId">The package to be uninstalled</param>
/// <param name="removeDependencies">
/// A boolean to indicate whether the dependency packages should be
/// uninstalled too.
/// </param>
void UninstallPackage(Project project, string packageId, bool removeDependencies);
}
IVsPathContext 介面
/// <summary>
/// NuGet path information specific to the current context (e.g. project context).
/// Represents captured snapshot associated with current project/solution settings.
/// Should be discarded immediately after all queries are done.
/// </summary>
public interface IVsPathContext
{
/// <summary>
/// User package folder directory. The path returned is an absolute path.
/// </summary>
string UserPackageFolder { get; }
/// <summary>
/// Fallback package folder locations. The paths (if any) in the returned list are absolute paths. If no
/// fallback package folders are configured, an empty list is returned. The item type of this sequence is
/// <see cref="string"/>.
/// </summary>
/// <remarks>Can be called from a background thread.</remarks>
IEnumerable FallbackPackageFolders { get; }
/// <summary>
/// Fetch a package directory containing the provided asset path.
/// </summary>
/// <param name="packageAssetPath">Absolute path to package asset file.</param>
/// <param name="packageDirectoryPath">Full path to a package directory.
/// <code>null</code> if returned falue is <code>false</code>.</param>
/// <returns>
/// <code>true</code> when a package containing the given file was found, <code>false</code> - otherwise.
/// </returns>
/// <example>
/// Suppose the project is a packages.config project and the following asset paths are provided:
///
/// - C:\src\MyProject\packages\NuGet.Versioning.3.5.0-rc1-final\lib\net45\NuGet.Versioning.dll
/// - C:\path\to\non\package\assembly\Newtonsoft.Json.dll
/// - C:\src\MyOtherProject\packages\NuGet.Core.2.12.0\lib\net40\NuGet.Core.dll
/// - C:\src\MyProject\packages\Autofac.3.5.2\lib\net40\Autofac.dll
/// - C:\src\MyProject\packages\Autofac.3.5.2\lib\net40\Autofac.Fake.dll
///
/// The result will be:
///
/// - C:\src\MyProject\packages\NuGet.Versioning.3.5.0-rc1-final
/// - null
/// - null
/// - C:\src\MyProject\packages\Autofac.3.5.2
/// - C:\src\MyProject\packages\Autofac.3.5.2
/// </example>
bool TryResolvePackageAsset(string packageAssetPath, out string packageDirectoryPath);
}
IVsPathContext2 介面
/// <summary>
/// NuGet path information specific to the current context (e.g. project context) or solution context
/// Represents captured snapshot associated with current project/solution settings.
/// Should be discarded immediately after all queries are done.
/// </summary>
public interface IVsPathContext2 : IVsPathContext
{
/// <summary>
/// Solution packages folder directory. This will always be set irrespective if folder actually exists or not.
/// The path returned is an absolute path.
/// </summary>
string SolutionPackageFolder { get; }
}
IVsPathContextProvider 介面
/// <summary>
/// A factory to initialize <see cref="IVsPathContext"/> instances.
/// </summary>
public interface IVsPathContextProvider
{
/// <summary>
/// Attempts to create an instance of <see cref="IVsPathContext"/>.
/// </summary>
/// <remarks>Can be called from a background thread.</remarks>
/// <param name="projectUniqueName">
/// Unique identificator of the project. Should be a full path to project file.
/// </param>
/// <param name="context">The path context associated with given project.</param>
/// <returns>
/// <code>True</code> if operation has succeeded and context was created.
/// False, otherwise, e.g. when provided project is not managed by NuGet.
/// </returns>
/// <throws>
/// <code>ArgumentNullException</code> if projectUniqueName is passed as null.
/// <code>InvalidOperationException</code> when it fails to create a context and return appropriate error message.
/// </throws>
bool TryCreateContext(string projectUniqueName, out IVsPathContext context);
}
IVsPathContextProvider2 介面
/// <summary>
/// A factory to initialize <see cref="IVsPathContext2"/> instances.
/// </summary>
public interface IVsPathContextProvider2 : IVsPathContextProvider
{
/// <summary>
/// Attempts to create an instance of <see cref="IVsPathContext2"/> for the solution.
/// </summary>
/// <remarks>This API is free-threaded, but APIs on the returned IVsPathContext2 may not be.</remarks>
/// <param name="context">The path context associated with this solution.</param>
/// <returns>
/// <code>True</code> if operation has succeeded and context was created.
/// <code>False</code> otherwise.
/// </returns>
/// <throws>
/// <code>InvalidOperationException</code> when it fails to create a context and return appropriate error message.
/// </throws>
bool TryCreateSolutionContext(out IVsPathContext2 context);
/// <summary>
/// Attempts to create an instance of <see cref="IVsPathContext2"/> for the solution.
/// </summary>
/// <remarks>This API is free-threaded, but APIs on the returned IVsPathContext2 may not be.</remarks>
/// <param name="solutionDirectory">
/// path to the solution directory. Must be an absolute path.
/// It will be performant to pass the solution directory if it's available.
/// </param>
/// <param name="context">The path context associated with this solution.</param>
/// <returns>
/// <code>True</code> if operation has succeeded and context was created.
/// <code>False</code> otherwise.
/// </returns>
/// <throws>
/// <code>ArgumentNullException</code> if solutionDirectory is passed as null.
/// <code>InvalidOperationException</code> when it fails to create a context and return appropriate error message.
/// </throws>
bool TryCreateSolutionContext(string solutionDirectory, out IVsPathContext2 context);
/// <summary>
/// Attempts to create an instance of <see cref="IVsPathContext"/> containing only the user wide and machine wide configurations.
/// If a solution is loaded, note that the values in the path context might not be the actual effective values for the solution.
/// If a customer has overriden the `globalPackagesFolder` key or cleared the `fallbackPackageFolders`, these values will be incorrect.
/// It is important to keep this scenario in mind when working with this path. To predict differences you can call this in combination with <see cref="TryCreateSolutionContext(out IVsPathContext2)"/>.
/// </summary>
/// <returns>
/// <code>True</code> if operation has succeeded and context was created.
/// <code>False</code> otherwise.
/// </returns>
/// <remarks>
/// This method can be safely invoked from a background thread. Do note that this method might switch to the UI thread internally, so be mindful of blocking the UI thread on this.
/// </remarks>
bool TryCreateNoSolutionContext(out IVsPathContext vsPathContext);
}
IVsProjectJsonToPackageReferenceMigrator 介面
/// <summary>
/// Contains methods to migrate a project.json based legacy project to PackageReference based project.
/// </summary>
public interface IVsProjectJsonToPackageReferenceMigrator
{
/// <summary>
/// Migrates a legacy Project.json based project to Package Reference based project. The result
/// should be casted to type <see cref="IVsProjectJsonToPackageReferenceMigrateResult"/>
/// The backup of the original project file and project.json file is created in the Backup folder
/// in the root of the project directory.
/// </summary>
/// <param name="projectUniqueName">The full path to the project that needs to be migrated</param>
Task<object> MigrateProjectJsonToPackageReferenceAsync(string projectUniqueName);
}
IVsSemanticVersionComparer 介面
/// <summary>
/// An interface for comparing two opaque version strings by treating them as NuGet semantic
/// versions.
/// </summary>
public interface IVsSemanticVersionComparer
{
/// <summary>
/// Compares two version strings as if they were NuGet semantic version
/// strings. Returns a number less than zero if <paramref name="versionA"/>
/// is less than <paramref name="versionB"/>. Returns zero if the two versions
/// are equivalent. Returns a number greater than zero if <paramref name="versionA"/>
/// is greater than <paramref name="versionB"/>.
/// </summary>
/// <remarks>This API is free-threaded.</remarks>
/// <param name="versionA">The first version string.</param>
/// <param name="versionB">The second version string.</param>
/// <exception cref="ArgumentNullException">If either version string is null.</exception>
/// <exception cref="ArgumentException">If either string cannot be parsed.</exception>
/// <returns>
/// A standard comparison integer based on the relationship between the
/// two provided versions.
/// </returns>
int Compare(string versionA, string versionB);
}
IVsNuGetProjectUpdateEvents 介面
/// <summary>
/// NuGet project update events.
/// This API provides means of tracking project updates by NuGet.
/// In particular, for PackageReference projects, updates to the assets file and nuget generated props/targets.
/// For packages.config projects, package installations will be tracked.
/// All events are fired from a threadpool thread.
/// </summary>
public interface IVsNuGetProjectUpdateEvents
{
/// <summary>
/// Raised when solution restore starts with the list of projects that will be restored.
/// The list will not include all projects. Some projects may have been skipped in earlier up to date check, and other projects may no-op.
/// </summary>
/// <remarks>
/// Just because a project is being restored that doesn't necessarily mean any actual updates will happen.
/// No heavy computation should happen in any of these methods as it'll block the NuGet progress.
/// </remarks>
event SolutionRestoreEventHandler SolutionRestoreStarted;
/// <summary>
/// Raised when solution restore finishes with the list of projects that were restored.
/// The list will not include all projects. Some projects may have been skipped in earlier up to date check, and other projects may no-op.
/// </summary>
/// <remarks>
/// Just because a project is being restored that doesn't necessarily mean any actual updates will happen.
/// No heavy computation should happen in any of these methods as it'll block the NuGet progress.
/// </remarks>
event SolutionRestoreEventHandler SolutionRestoreFinished;
/// <summary>
/// Raised when particular project is about to be updated.
/// For PackageReference projects, this means an assets file or a nuget temp msbuild file write (nuget.g.props or nuget.g.targets). The list of updated files will include the aforementioned.
/// If a project was restored, but no file updates happen, this event will not be fired.
/// For packages.config projects, this means that the project file was changed.
/// </summary>
/// <remarks>
/// No heavy computation should happen in any of these methods as it'll block the NuGet progress.
/// </remarks>
event ProjectUpdateEventHandler ProjectUpdateStarted;
/// <summary>
/// Raised when particular project update has been completed.
/// For PackageReference projects, this means an assets file or a nuget temp msbuild file write (nuget.g.props or nuget.g.targets). The list of updated files will include the aforementioned.
/// If a project was restored, but no file updates happen, this event will not be fired.
/// For packages.config projects, this means that the project file was changed.
/// </summary>
/// <remarks>
/// No heavy computation should happen in any of these methods as it'll block the NuGet progress.
/// </remarks>
event ProjectUpdateEventHandler ProjectUpdateFinished;
}
/// <summary>
/// Defines an event handler delegate for solution restore start and end.
/// </summary>
/// <param name="projects">List of projects that will run restore. Never <see langword="null"/>.</param>
public delegate void SolutionRestoreEventHandler(IReadOnlyList<string> projects);
/// <summary>
/// Defines an event handler delegate for project updates.
/// </summary>
/// <param name="projectUniqueName">Project full path. Never <see langword="null"/>. </param>
/// <param name="updatedFiles">NuGet output files that may be updated. Never <see langword="null"/>.</param>
public delegate void ProjectUpdateEventHandler(string projectUniqueName, IReadOnlyList<string> updatedFiles);
}
IVsSolutionRestoreService 介面
/// <summary>
/// Represents a package restore service API for integration with a project system.
/// </summary>
public interface IVsSolutionRestoreService
{
/// <summary>
/// A task providing last/current restore operation status.
/// Could be null if restore has not started yet.
/// </summary>
/// <remarks>
/// This task is a reflection of the current state of the current-restore-operation or
/// recently-completed-restore. The usage of this property will be to continue,
/// e.g. to build solution or something) on completion of this task.
/// Also, on completion, if the task returns false then it means the restore failed and
/// the build task will be terminated.
/// </remarks>
Task<bool> CurrentRestoreOperation { get; }
/// <summary>
/// An entry point used by CPS to indicate given project needs to be restored.
/// </summary>
/// <param name="projectUniqueName">
/// Unique identifier of the project. Should be a full path to project file.
/// </param>
/// <param name="projectRestoreInfo">Metadata <see cref="IVsProjectRestoreInfo"/> needed for restoring the project.</param>
/// <param name="token">Cancellation token.</param>
/// <returns>
/// Returns a restore task corresponding to the nominated project request.
/// NuGet will batch restore requests so it's possible the same restore task will be returned for multiple projects.
/// When the requested restore operation for the given project completes the task will indicate operation success or failure.
/// </returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="projectUniqueName" /> is not the path of a project file.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="projectRestoreInfo" /> is <c>null</c>.</exception>
/// <exception cref="OperationCanceledException">Thrown if <paramref name="token" /> is cancelled.</exception>
Task<bool> NominateProjectAsync(string projectUniqueName, IVsProjectRestoreInfo projectRestoreInfo, CancellationToken token);
}
IVsSolutionRestoreService2 介面
/// <summary>
/// Represents a package restore service API for integration with a project system.
/// </summary>
public interface IVsSolutionRestoreService2
{
/// <summary>
/// An entry point which allows non-NETCore SDK based projects to indicate given project needs to be restored.
/// </summary>
/// <param name="projectUniqueName">
/// Unique identificator of the project. Should be a full path to project file.
/// </param>
/// <param name="token">Cancellation token.</param>
/// <returns>
/// Returns a restore task corresponding to the nominated project request.
/// NuGet will batch restore requests so it's possible the same restore task will be returned for multiple projects.
/// When the requested restore operation for the given project completes the task will indicate operation success or failure.
/// </returns>
Task<bool> NominateProjectAsync(string projectUniqueName, CancellationToken token);
}
IVsSolutionRestoreService3 介面
/// <summary>
/// Represents a package restore service API for integration with a project system.
/// </summary>
public interface IVsSolutionRestoreService3
{
/// <summary>
/// A task providing last/current restore operation status.
/// Could be null if restore has not started yet.
/// </summary>
/// <remarks>
/// This task is a reflection of the current state of the current-restore-operation or
/// recently-completed-restore. The usage of this property will be to continue,
/// e.g. to build solution or something) on completion of this task.
/// Also, on completion, if the task returns false then it means the restore failed and
/// the build task will be terminated.
/// </remarks>
Task<bool> CurrentRestoreOperation { get; }
/// <summary>
/// An entry point used by CPS to indicate given project needs to be restored.
/// This entry point also handles PackageDownload items
/// </summary>
/// <param name="projectUniqueName">
/// Unique identifier of the project. Should be a full path to project file.
/// </param>
/// <param name="projectRestoreInfo">Metadata <see cref="IVsProjectRestoreInfo2"/> needed for restoring the project.</param>
/// <param name="token">Cancellation token.</param>
/// <returns>
/// Returns a restore task corresponding to the nominated project request.
/// NuGet will batch restore requests so it's possible the same restore task will be returned for multiple projects.
/// When the requested restore operation for the given project completes the task will indicate operation success or failure.
/// </returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="projectUniqueName" /> is not the path of a project file.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="projectRestoreInfo" /> is <c>null</c>.</exception>
/// <exception cref="OperationCanceledException">Thrown if <paramref name="token" /> is cancelled.</exception>
Task<bool> NominateProjectAsync(string projectUniqueName, IVsProjectRestoreInfo2 projectRestoreInfo, CancellationToken token);
}
IVsSolutionRestoreService4 介面
/// <summary>
/// Represents a package restore service API for integration with a project system.
/// Implemented by NuGet.
/// </summary>
public interface IVsSolutionRestoreService4 : IVsSolutionRestoreService3
{
/// <summary>
/// A project system can call this service (optionally) to register itself to coordinate restore. <br/>
/// Each project can only register once. NuGet will call into the source to wait for nominations for restore. <br/>
/// NuGet will remove the registered object when a project is unloaded.
/// </summary>
/// <param name="restoreInfoSource">Represents a project specific info source</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <exception cref="InvalidOperationException">If the project has already been registered.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="restoreInfoSource"/> is null. </exception>
/// <exception cref="ArgumentException">If <paramref name="restoreInfoSource"/>'s <see cref="IVsProjectRestoreInfoSource.Name"/> is <see langword="null"/>. </exception>
Task RegisterRestoreInfoSourceAsync(IVsProjectRestoreInfoSource restoreInfoSource, CancellationToken cancellationToken);
}
IVsProjectRestoreInfoSource 介面
/// <summary>
/// Represents a package restore service API for integration with a project system.
/// Implemented by the project-system.
/// </summary>
public interface IVsProjectRestoreInfoSource
{
/// <summary>
/// Project Unique Name.
/// Must be equivalent to the name provided in the <see cref="IVsSolutionRestoreService3.NominateProjectAsync(string, IVsProjectRestoreInfo2, CancellationToken)"/> or equivalent.
/// </summary>
/// <remarks>Never <see langword="null"/>.</remarks>
string Name { get; }
/// <summary>
/// Whether the source needs to do some work that could lead to a nomination. <br/>
/// Called frequently, so it should be very efficient.
/// </summary>
bool HasPendingNomination { get; }
/// <summary>
/// NuGet calls this method to wait on a potential nomination. <br/>
/// If the project has no pending restore data, it will return a completed task. <br/>
/// Otherwise, the task will be completed once the project nominates. <br/>
/// The task will be cancelled, if the source decide it no longer needs to nominate (for example: the restore state has no change) <br/>
/// The task will be failed, if the source runs into a problem, and it cannot get the correct data to nominate (for example: DT build failed) <br/>
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task WhenNominated(CancellationToken cancellationToken);
}
IVsSolutionRestoreStatusProvider 介面
/// <summary>
/// Provides the status of IVsSolutionRestore.
/// </summary>
public interface IVsSolutionRestoreStatusProvider
{
/// <summary>
/// IsRestoreCompleteAsync indicates whether or not automatic package restore has pending work.
/// Automatic package restore applies for both packages.config and PackageReference projects.
///
/// Returns true if all projects in the solution that require nomination have been nominated for restore and all pending restores have completed.
/// The result does not indicate that restore completed successfully, a failed restore will still return true.
/// </summary>
/// <remarks>
/// Special cases:
/// * An empty solution will return true.
/// * If no solution is open this will true.
/// * An invalid project that does not provide restore details will cause this to return false since restore will not run for that project.
///
/// Restores running due to Install/Update/Uninstall operations are NOT included in this status. Status here is limited to IVsSolutionRestoreService.
/// </remarks>
Task<bool> IsRestoreCompleteAsync(CancellationToken token);
}