December 7, 2010

Creating a NuGet Package

NuGet is a package manager for .NET that was recently released by Microsoft as a CTP. This library is similar to gems or cpan or similar libraries in other languages. I decided to try my hand at creating a HelloWorld package.

First I needed a package. My original idea was to create something useful enough to contribute to the public feed of NuGet packages. I started by creating the Shelf library, which is a small set of extension methods. Notably, I created the Each<T> method that extends IEnumerable<T>. It takes an Action<T>, invoking the action for every item in the sequence. It's a trivial and small library at the moment, but imagine it is something useful and complicated. The library itself isn’t the point here.

Create the package “manifest” (my term).

<package>
  <metadata>
    <id>shelf</id>
    <version>2010.1203.2330.42313</version>
    <authors>Kwak</authors>
    <description>Shelf is a library of common extension methods</description>
    <language>en-US</language>
  </metadata>
  <files>
    <file src="Shelf\bin\Release\*.dll" target="lib" />
    <file src="Shelf\bin\Release\*.pdb" target="lib" />
  </files>
</package>

The documentation says the files element is optional. It seems I didn’t discover the “convention” they were speaking about in the documentation. I needed it.

I ran the command-line tool nuget.exe passing it the pack command and the package manifest. It spat out the packaged file (BTW, you can use just about any zip tool to browse the contents of the package).

There are couple of different ways to deploy the package. Submitting your package for inclusion in the public feed is one option. You can put the file on any accessible URL. The NuGet source includes a “Server” utility. Until my library grows to a point where it’s not laughably trivial, I opted for just putting it in my file system and pointing the package manager to folder. Phil Haack has a great post explaining the deployment options.

So with my package (shelf.2010.1203.2330.42313.nupkg) located in my local packages folder, anytime I want to make use of the shelf library, I simply go to the package manager console and type

Install-Package shelf
NuGet goes off, makes sure it has the latest package, adds the package folder to my source if it doesn't already exist, downloads (copies) the assembly, and adds the reference to the project.

Here are some of the references, I’ve found useful:


Conclusion: Piece of cake and terribly useful for consumers of your library.

No comments:

Post a Comment