如何将 Nuget 包添加到我的 Visual Studio 扩展中的项目?

How can I add a Nuget package to a project in my Visual Studio extension?

我正在构建一个 Visual Studio 扩展,我想在用户单击按钮时添加一个特定的 Nuget 包。我查看了 Visual Studio SDK,似乎没有关于如何执行此操作的文档。有什么想法吗?

您可以使用 IVsPackageInstaller 从 Visual Studio.

中安装 NuGet 包

安装 NuGet.VisualStudio NuGet 包,然后使用 MEF 访问它。

//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 站点上的文档:

https://docs.microsoft.com/en-us/nuget/visual-studio-extensibility/nuget-api-in-visual-studio