Search code examples
visual-studionugetvisual-studio-extensions

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


I'm building a Visual Studio extension and I want to add a Specific Nuget package when the user clicks a button. I looked around the Visual Studio SDK and there seems no documentation on how to do this. Any ideas?


Solution

  • There is an IVsPackageInstaller you can use to install a NuGet package from within Visual Studio.

    Install the NuGet.VisualStudio NuGet package and then use MEF to get access to it.

    //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();
    

    The above was extracted from the documentation on the NuGet site:

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