Search code examples
visual-studionuget-packageenvdtevisual-studio-templates

Adding NuGet packages from nuget.org in a custom VS item template


I am trying to add NuGet packages automatically when adding a custom item template in Visual Studio. The packages need to be referenced from nuget.org, deploying them locally in the ItemTemplate-Zipfiles is unfortunately no option.

What I have tried so far:

1.) Altering the packages.config programatically. As this requires the project to be reloaded and manual intervention to install the added packages, this is not really feasible

2.) Using NuGet.VisualStudio.Interop in the template wizard as well as adding it to the vstemplate file requires the NuGet packages to be stored locally. Since I need to them to be installed from nuget.org, this is no option either.

3.) Using the NuGet-API doesn't seem to work either, since it does not take the "project" parameter passed to it from envdte or vslangproj.

Any ideas would be very welcome.


Solution

  • Finally resolved it with this code:

    List<string> packagesToInstall = new List<string>();
    packagesToInstall.Add("SomeNuGetPackageIdentifier");
    var componentModel = (IComponentModel)Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel));
    IVsPackageInstaller2 installer = componentModel.GetService<IVsPackageInstaller2>();
    
    //Loop through the list of Strings and install the Packages.
    foreach (string package in packagesToInstall)
    {
        try
        {
            installer.InstallLatestPackage(null, vsProj.Project, package, false, false);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            continue;
        }
    }