Automating your NuGet package

NuGet is a great way of handling dependencies. It isn't perfect, but if you've experienced the days of DLL hell, you know NuGet hell is at least more manageable.

One step that I've found was always missing, is automating the publishing of your NuGet package. We've played around with different scripts in the past, bat files and PowerShell files, but it was always a bit hacked together. And it always required several manual steps when a new project was created. I hate repeating manual work.

We found (or rather my colleague Stefaan found) a NuGet package that does exactly that, and integrates nicely with our archaic TFS build over which we have little control.

The package is aptly named NuGet Package Builder Tool and installs easily.

Setting it up

First, add the NuGet package in Visual Studio. The package will have changed your csproj file (or vbproj of fsproj) to include an extra MSBuild target. Nothing to worry about for now. Unfortunately, it doesn't clean this up when you uninstall the package.

There will also be a nuspec file in your project. The cool thing is the Id and the Version will automatically be replaced when building. The Id will be the name of your project (so change that if you want), and the version will be the AssemblyVersion.

The nice thing about this, is that our build automatically changes the AssemblyVersion based on a TFS Label. The project is compiled after that, so our NuGet packages always have the same version as the TFS Label. All automatically. Awesome.

Finally, there's a JSON file included, where you can configure this. We decided to not publish when building locally, but you can add an MSBuild argument to your TFS build so that it does publish when building.

There's more to configure (like whether or not to include symbols), but it's all explained in the JSON file.

The magic

The cool thing about this package is that it automatically resolves dependencies. Except for framework dependencies, you have to add those to the nuspec file yourself.

When you have project references, these assemblies will be added to the NuGet package. But if these references have there own nuspec file, they won't be included. Rather, a dependency will be added to the nuspec file, with the correct minimal version number. Again, no hassle, no thinking. Awesome.

In short:

  • Add the package to the project(s) you want to publish as NuGet package
  • Modify the nuspec file
  • Modify the json file
  • If necessary, modify your build
  • Pat yourself on the back for automating another step in your workflow