65.9K
CodeProject is changing. Read more.
Home

Installing a NuGet Package Programmatically

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (4 votes)

Sep 22, 2014

CPOL

1 min read

viewsIcon

11571

How to install a Nuget package programmatically

I've been struggling for some time to make NuGet work for my online .NET IDE project, Chpokk. The good news is that there turned out to be a command line tool, NuGet.exe, which can be used on a build server, so I though I'd just use its functionality. The bad news is that it turned out that it only downloaded packages, not modifying the project. Then the good news is that there's ProjectManager class, which can handle the required modifications to the project. And of course, there's the bad news -- while this guy downloads the packages, it doesn't copy the unzipped files to the package folder from the temporary location. Fortunately, the final news was good -- the ProjectManager class proved to be extensible enough to make it work. Although I haven't tested some advanced stuff, like ps scripts or config transforms, it works for most situations, and extending it would be pretty simple.

Here's the main part of the code:

public void InstallPackage(string packageId, string projectPath, string targetFolder = null) {
	var packagePathResolver = new DefaultPackagePathResolver(targetFolder);
	var packagesFolderFileSystem = new PhysicalFileSystem(targetFolder);
	var projectSystem = new BetterThanMSBuildProjectSystem(projectPath) 
	{ Logger = _console };
	var localRepository = new BetterThanLocalPackageRepository
	(packagePathResolver, packagesFolderFileSystem, projectSystem);
	var projectManager = new ProjectManager
	(_packageRepository, packagePathResolver, projectSystem,
     localRepository) {Logger = _console};
 
	projectManager.PackageReferenceAdded += (sender, args) => args.Package.GetLibFiles()
    .Each(file => SaveAssemblyFile(args.InstallPath, file));
	projectManager.AddPackageReference(packageId);
	projectSystem.Save();
}

The most work is done by the ProjectManager class. I had to add three extensions though. First, in the PackageReferenceAdded handler, I make sure that the assembly files are saved to install path. Second, I extend the MSBuildProjectSystem class in order to add the content files to the project. Last, I'm subclassing the LocalPackageRepository class. This class is used, in particular, for checking whether a package is already installed. The implementation just checked that either a *.nuspec or *.nupkg file existed.

You can find a working project here. Download the project and build a console executable that, when run, installs the NUnit (or another, if you add an argument) package to the "testPackages" folder and adds a reference to the project.

Happy Nuggeting!