Project Files and NuGet: The Parts Catalogue

Project Files and NuGet: The Parts Catalogue in C#: A workshop that builds anything non-trivial does not machine its own bolts.

The Analogy: The Parts Catalogue

A workshop that builds anything non-trivial does not machine its own bolts. It keeps a parts catalogue: every component has a part number, a revision, and a note about what else it needs to work. When you write "M8 × 40, rev 3" on a build sheet, the storeroom knows exactly what to hand you, and anyone reading the sheet a year later can order the identical part.

A .csproj is that build sheet, and NuGet is the catalogue. <PackageReference Include="Serilog" Version="4.2.0" /> is a part number and a revision, written down in a file that travels with your code. The point is not that typing it is easier than downloading a DLL — it is that the sheet is complete: given the project file, any machine anywhere can assemble exactly the same set of parts.

Catalogues have a complication that bolts do not. A part can require other parts, and those can require others still, so ordering one thing quietly orders a dozen. Worse, two of your components may each demand a different revision of the same sub-part — and you cannot fit two revisions of the same bolt in the same hole. Understanding how NuGet resolves that argument, and how to see what it decided, is most of what separates a project that upgrades smoothly from one nobody dares touch.

The other half is discipline about the sheet itself. Version numbers scattered across fifteen project files drift apart; version numbers declared once in a shared file cannot. Most of this lesson is about the small number of files that make a multi-project repository behave like one coherent workshop instead of fifteen independent ones.


Syntax or Core Structure

A modern project file is short, and almost every line is a decision:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <InvariantGlobalization>true</InvariantGlobalization>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Serilog" Version="4.2.0" />
    <PackageReference Include="Dapper" Version="2.1.66" />

    <!-- Analysers are build-time only: never flow to consumers. -->
    <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="../Shop.Core/Shop.Core.csproj" />
  </ItemGroup>

</Project>

The everyday commands:

dotnet add package Serilog --version 4.2.0
dotnet remove package Dapper
dotnet list package
dotnet list package --outdated
dotnet list package --vulnerable --include-transitive

Output: (abridged - column widths vary with the longest name)

Project 'Shop.Cli' has the following package references
   [net9.0]:
   Top-level Package        Requested   Resolved
   > Dapper                 2.1.66      2.1.66
   > Serilog                4.2.0       4.2.0
   > StyleCop.Analyzers     1.2.0-b...  1.2.0-beta.556

   Transitive Package                   Resolved
   > System.Runtime.CompilerServices...  4.3.0

Two columns, two different questions. Requested is what your project file asks for; Resolved is what NuGet actually picked. They differ whenever a transitive dependency demands something higher, and the gap between them is where upgrade surprises live — a package you never named can raise the resolved version of one you did.

What is not in the file is as informative as what is. There is no list of .cs files: the SDK includes every .cs under the project directory automatically. There is no output path, no assembly name, no list of framework assemblies. Everything in a modern .csproj is either a decision you made or a dependency you declared, which is why a hundred-line project file is usually a sign that something needs cleaning up.

The PrivateAssets block on the analyser is the one piece of ceremony worth learning by heart. Without it, a library that references StyleCop passes that reference on to everything that references it, so consumers inherit your lint rules. PrivateAssets=all means "I need this to build; nobody downstream does."


Technical Depth: Versions, Transitives and Conflicts

Version syntax

WrittenMeans
4.2.0Minimum 4.2.0 - NuGet may resolve higher
[4.2.0]Exactly 4.2.0, nothing else
[4.2.0,5.0.0)At least 4.2.0, below 5.0.0
4.*Floating: newest 4.x at restore time
4.2.0-beta.3A prerelease; never matched by a stable range

The critical surprise is that a plain 4.2.0 is a minimum, not a pin. NuGet's rule is nearest-wins for direct references, highest-wins for transitive ones: your direct reference takes priority, but among transitive demands the highest version wins for everybody. Floating versions (4.*) make restores non-reproducible and should stay out of anything you ship.

Seeing the whole graph

dotnet list package --include-transitive     # everything, direct and inherited
dotnet nuget why Shop.Cli Newtonsoft.Json    # who dragged this in?

dotnet nuget why is the answer to "I never referenced this — where did it come from?", printing the chain from your project down to the package.

Where properties should live

Directory.Build.props at the repository root is imported by every project below it, so shared settings are written once:

<Project>
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <LangVersion>latest</LangVersion>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <EnableNETAnalyzers>true</EnableNETAnalyzers>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
    <Deterministic>true</Deterministic>
  </PropertyGroup>
</Project>

MSBuild imports it before the project body, so an individual project can still override any value. Directory.Build.targets is the same idea applied after the project, for anything that needs the project's own values to already be set.

Restore, lock files, and reproducibility

obj/project.assets.json records the resolved graph after each restore, and it is regenerated freely. For a build that must resolve identically months later, opt into a lock file:

<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>

That produces packages.lock.json, which you commit. CI then runs dotnet restore --locked-mode, which fails rather than silently resolving something new — the difference between "the build changed" and "the build broke, here is why".

Feeds and supply chain

nuget.config beside the solution controls where packages come from:

<configuration>
  <packageSources>
    <clear />                                <!-- ignore machine-level sources -->
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>

<clear /> is the security-relevant line: without it, a source configured on the machine can supply a package your repository never intended, which is the mechanism behind dependency-confusion attacks. Keep NuGetAudit on (it is by default on modern SDKs) so restore reports known vulnerabilities, run dotnet list package --vulnerable --include-transitive in CI, and check a new dependency's download count, repository link and release cadence before adding it — a typo-squatted name one character from a popular package is a real and recurring attack.

Packing a library

<PropertyGroup>
  <PackageId>Shop.Core</PackageId>
  <Version>1.4.0</Version>
  <Authors>Shop Team</Authors>
  <Description>Domain types for the Shop sample.</Description>
  <PackageLicenseExpression>MIT</PackageLicenseExpression>
  <RepositoryUrl>https://github.com/example/shop</RepositoryUrl>
  <PublishRepositoryUrl>true</PublishRepositoryUrl>
  <IncludeSymbols>true</IncludeSymbols>
  <SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>

Then dotnet pack -c Release produces the .nupkg, and dotnet nuget push sends it to a feed. Follow SemVer honestly: patch for fixes, minor for additions, major for anything that breaks a caller — consumers rely on it to decide whether an upgrade is safe.


Real World Example: One Version, Fifteen Projects

A solution has grown to fifteen projects. Serilog appears in nine of them, at four different versions, and nobody can say which one production actually runs. Central Package Management fixes this with two files.

Directory.Packages.props at the repository root — the single catalogue:

<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
    <CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
  </PropertyGroup>

  <ItemGroup>
    <PackageVersion Include="Serilog" Version="4.2.0" />
    <PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />
    <PackageVersion Include="Dapper" Version="2.1.66" />
    <PackageVersion Include="FluentAssertions" Version="7.0.0" />
    <PackageVersion Include="xunit" Version="2.9.3" />
  </ItemGroup>

  <!-- Every test project gets these, with no per-project ceremony. -->
  <ItemGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
    <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
  </ItemGroup>
</Project>

Every project file then names the package and nothing else:

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="Serilog" />           <!-- no Version attribute -->
    <PackageReference Include="Dapper" />
  </ItemGroup>
</Project>

Adding a version back into a project file is now an error, which is the whole point:

dotnet build

Output:

Shop.Cli.csproj : error NU1008: Projects that use central package version
management should not define the version on the PackageReference items but
on the PackageVersion items: Serilog.

NU1008 is the guardrail. Before central management, a developer in a hurry could pin one project to an older Serilog and nobody would notice for six months; now the build refuses, and the only place a version can change is the one file a reviewer is watching. Upgrading Serilog across all fifteen projects becomes a one-line diff — which is also the honest cost of this design: you cannot stage an upgrade project by project, so a breaking change lands everywhere at once.

CentralPackageTransitivePinningEnabled extends the same control one level deeper. Normally a transitive dependency resolves to whatever the highest demand happens to be; with pinning on, a PackageVersion entry constrains transitive resolution too. That is how you deal with the awkward case where a vulnerability advisory names a package you never referenced — you add a PackageVersion for it, and every project picks up the fixed version without any of them declaring a dependency they do not have.

The conditional ItemGroup is worth stealing. $(MSBuildProjectName.EndsWith('.Tests')) is an MSBuild property function, evaluated per project, so test-only dependencies are described once by convention rather than copied into every test project. The same trick lives happily in Directory.Build.props for properties: IsPackable false for tests, coverage settings only where they apply.

One caveat about ordering. Directory.Packages.props and Directory.Build.props are found by walking up from each project until the first match, and the search stops there. A nested Directory.Build.props in src/ therefore silently replaces the root one unless it explicitly imports its parent — which is why the standard first line of a nested props file is <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />.


Common Mistakes

  1. Treating Version="4.2.0" as a pin. It is a minimum; a transitive dependency can raise it. Use [4.2.0] for an exact pin, and a lock file for reproducibility.
  2. Using floating versions in a shipped project. 4.* means two restores a week apart can produce different builds.
  3. Letting analyser and build-only packages flow to consumers. Add PrivateAssets=all so your lint rules stay yours.
  4. Copying package versions into every project file. They drift apart, and nobody can answer "which version does production use?". Centralise them.
  5. Omitting <clear /> from nuget.config. A machine-level feed can then supply a package your repository never intended — the dependency-confusion attack in one line.
  6. Adding a package without looking at it. Check the download count, the repository link, the licence, and the spelling; typo-squatted names are a real supply-chain vector.
  7. Referencing a project's built DLL instead of the project. ProjectReference gives you build ordering, transitive dependencies and matching configuration; a raw Reference to a file gives you none of them.
  8. Ignoring dotnet list package --vulnerable. Advisories usually name transitive packages, so run it with --include-transitive and run it in CI, not by hand once a year.

Best Practices

  • Keep project files short: shared settings in Directory.Build.props, package versions in Directory.Packages.props, and only genuine per-project decisions in the .csproj.
  • Turn on central package management from the start of a multi-project repository — retrofitting it means reconciling every drifted version at once.
  • Commit packages.lock.json and restore with --locked-mode in CI so dependency changes are always a visible diff.
  • Pin your feeds with <clear /> and an explicit source list, and keep NuGetAudit enabled.
  • Run dotnet list package --outdated and --vulnerable --include-transitive on a schedule, and treat vulnerable output as a build failure.
  • Use dotnet nuget why before removing anything you did not add yourself.
  • Follow SemVer honestly in libraries you publish, and fill in Description, RepositoryUrl and a licence expression so consumers can evaluate the package.
  • Prefer ProjectReference inside a repository and PackageReference across repository boundaries; never reference a loose DLL.

Practice Exercises

  1. Take a two-project solution, move TargetFramework and Nullable into Directory.Build.props, and confirm both projects still build with those lines deleted from their .csproj files.
  2. Convert the same solution to central package management. Then add a Version back into one PackageReference, run dotnet build, and quote the error you get.
  3. Add a package with a deep dependency tree, run dotnet list package --include-transitive, and pick one transitive package to trace with dotnet nuget why. Write down the chain.
  4. Enable RestorePackagesWithLockFile, commit the lock file, then bump a package version in Directory.Packages.props and run dotnet restore --locked-mode. Explain the failure and the correct way to update the lock file.