How to Pin NuGet Dependencies 🐤

If you code in .Net languages such as C#, are you sure you're using the same dependencies as your colleague? If not, you might want to add a lock file to your project to pin them!

2 min read
How to Pin NuGet Dependencies 🐤
Photo by adoproducciones on Pixabay

In my new job, I recently came across a C# project that was not working on my workstation as expected. Since I couldn't figure what was wrong and didn't have much experience with .Net projects, I started to suspect that I didn't have the same dependencies as everyone else...

In the past, I have encountered two applications, one in PHP and another in Java, that had versions of dependencies that were causing problems. While I had the latest version of one of the dependencies, my coworkers had a much older version and it worked for them but not for me. It's only when they install the project from scratch (and pull the same versions as me) that they acquire the problem... 😬

And when we don't expect this type of problem, you can spend a lot of time looking for the issue... Trust me on this one! 😅

One solution to make sure everyone has the same dependencies is a lock file. What is that? It's simply a file that lists information (such as version and content hash) for each dependency used by the project: the direct dependencies (the dependencies you use) and the transitive dependencies (the dependencies of the dependencies). 🥴

Since nothing in my project looks like a lock file, I was wondering if this concept exists in the C# environment. And yes, it does exist and it's even recommended by Microsoft!

For C# applications, it can be enabled by adding the following code to the [APPLICATION].csproj file:

<PropertyGroup>
  <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
</PropertyGroup>
The code needed to activate lock file in .Net projects.

The next time your project is built, it will generate a packages.lock.json file that you will need to commit to have reproducible builds. And if you have multiple projects inside your Visual Studio solution, don't forget to add the code to each!

And for those who are wondering if the lock file helped me with my problem, unfortunately not! But my concern will certainly help us to not encounter this type of problem in the future! 😀  

Happy locking! 😆