C# Libraries – Best Practices for Sharing Class Libraries Between Solutions

asp.net-mvcc

A useful principle in computer programming is DRY (Don’t Repeat Yourself). I am trying to follow this rule as I am refactoring a large .NET Framework MVC project by breaking it down into separate solutions.

One problem that I am still unable to resolve to my satisfaction involves a set of C# libraries (static functions, Authorization Attribute overrides, and others) that need to be identical in each solution. These solutions are pushed to TFS source control, which means that linked projects outside the solution will not copy to source control. In other words, all projects need to be contained within the solution.

This image is a (highly simplified) illustration of what I am trying to describe. My intention is for the top solution "C# .NET Framework Solution" to have the "master copy". The other solutions rely on those same libraries. While I can "link" to those solutions, that approach only works on the PC where those solutions are authored. Projects linked to outside the solution cannot be pushed (in my experience) to source control.

enter image description here

The approach I am using – which does work as intended – is to maintain my “master copy” of C# class libraries in a specific solution. I have manually copied the specific C# class library projects to each of the solutions that need them. The good thing is that because the “copied” project exists in the solution, the solution can be pushed to source control in the intended manner. The bad thing is that this is a “copy”.

My one question is this: is there a way to have the best of both worlds, where the C# library project exists in the solution, but if I make a change to the “master copy” all the “copies” in the other solutions are synced? Why would I want this? Imagine if the code does change in one or more of those libraries and I (or my successor) forgets to make those changes in all those other solutions? What if I make a mistake in one or more of the copies?

Is my current technique the only option I have, or is there a different way for me not to break the DRY principle?

Best Answer

Shortest answer ever : publish reusable library with required dependencies as NuGet package and install it wherever you need. It will help you in versioning as well.

If your class library is .NET Framework, converting it to .NET Standard will solve many problems involved with publishing it as a NuGet package. Visual Studio 2017 makes it very easy to do this, but only if it is .NET Standard.

To serve the NuGet packages, there are some options:

  • Copy the .nupkg file to a shared folder location. In Visual Studio, you can configure NuGet to read from that folder location Tools > Options > NuGet Packge Manager > Package Sources.
  • Follow the instructions on Hosting your own NuGet feeds.