How to pack shared projects into a single nuget (.nupkg) file

Ever get that feeling your doing too much work and missing out on too much fun? Using shared libraries helps with that and bundling them in your nugets helps even more...

Created: 6/6/2022, 11:02:00 AM \ Updated: 6/6/2022, 11:02:00 AM

START()

Lets say you have a dotnet solution containg more than one project. You need to pack these projects into a single nuget file.

.
├── MySharedProject/
│ └── *.csproj
├── MySharedProject.Data/
│ └── *.Data.csproj
└── MySharedProject.sln

HOW

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Your Properties Here -->
<Name>LibraryProject</Name>
<TargetsForTfmSpecificBuildOutput>
$(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage
<TargetsForTfmSpecificBuildOutput>
</PropertyGroup>
<!-- Some other installed Nugets -->
<ItemGroup>
<ProjectReference Include="..\LibraryProject.Data\LibraryProject.Data.csproj" />
</ItemGroup>
<Target DependsOnTargets="ResolveReferences" Name="CopyProjectReferencesToPackage">
<ItemGroup>
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget', 'ProjectReference'))"/>
</ItemGroup>
</Target>
</Project>

Deep Dives 🌊

What the !%#&@ is TargetsForTfmSpecificBuildOutput???

Adds files (ie .dlls) from a path into the .nupkg file

The Target & “BuildOutputInPackage” ensures that TargetsForTfmSpecificBuildOutput collects the correct .dll file AND all of its own references! hate to be missing a third data package nested inside out lovely LibraryProject.Data.csproj

Testing

A great way to see it works without directly importing it into another libary is to use Nuget Package Explorer

After packaging, open the .nupkg file using this tool to see whats contained the the bundle. If everything is there then we have successfully made our lives simpler 😊

HOW DEEP DOES IT GO?

A MSbuild “Target” groups tasks to be ran together at a certain build stage. You can reference MSB variables in these targets to do cool things like “ReferenceCopyLocalPaths” allows you to gather the array of matched items and operate on it (in our case pack them into a single nuget for portability!)

profil

Christian Claudeaux

Full Stack Developer

Composer, Coder, Creator. Microsoft and open source web development Technology specialist about.