我正在开发Visual Studio扩展,并且我想在NuGet安装或卸载后执行一些逻辑。有没有我可以监控的事件?我在IVsHierarchy界面中尝试过OnItemAdded和OnItemDeleted,但问题是每次安装/卸载时它会执行多次,因为要添加或删除到解决方案的文件数量。我想在NuGet过程完成后触发事件。
答案 0 :(得分:2)
它可以像下面的代码一样简单。只需确保使用https://dotnet.myget.org/F/nuget-build/api/v3/index.json作为Nuget Feed即可获得NuGet.VisualStudio最新软件包(v4.0.0-rc3-2137)。
[Import]
private IVsPackageInstallerEvents packageInstallerEvents;
[Import]
private IVsPackageInstallerProjectEvents packageInstallerProjectEvents;
private string currentBatchId;
private Dictionary<string, string> packagesMetadata;
public void BindNuGetPackageEvents()
{
packageInstallerProjectEvents.BatchStart += (projectMetadata) =>
{
// preserve current batch id or project name to compare with batch end event
currentBatchId = projectMetadata.BatchId;
Console.WriteLine("Current Project Name : " + projectMetadata.ProjectName);
};
packageInstallerEvents.PackageInstalled += (metadata) =>
{
// package being insalled in current project
// Save package metadata to use at batch end event
packagesMetadata.Add(metadata.Id, "installed");
};
packageInstallerEvents.PackageUninstalled += (metadata) =>
{
// package being uninstalled in current project
// Save package metadata to use at batch end event
packagesMetadata.Add(metadata.Id, "uninstalled");
};
packageInstallerProjectEvents.BatchEnd += (projectMetadata) =>
{
if (currentBatchId == projectMetadata.BatchId)
{
// Now you can use your packages metadata saved during packageinstalled or packageuninstalled events
foreach (var packageName in packagesMetadata.Keys)
{
Console.WriteLine(string.Format("Package {0} was {1}", packageName, packagesMetadata[packageName]));
}
}
};
}
答案 1 :(得分:1)
您可以在Visual Studio中使用NuGet API并侦听BagInstalling或PackageInstalled等NuGet事件。但请确保您在批处理模式下使用这些事件,并且还从NuGet IVsPackageInstallerProjectEvents接口侦听BatchStart和BatchEnd,以便它不会降低NuGet性能。
您可以在NuGet blogpost上找到有关这些API here的更多详细信息。
理想情况下,当您收到BatchStart事件时,您将继续执行IVInPackageInstallerEvents事件,如PackageInstalling,PackageInstalled等,并在收到BatchEnd事件后应用这些事件。