NuGet is the package management system for the .NET platform. It allows developers to share, version, and consume modular libraries across projects.
1. Package Installation & Management via CLI
# Add a specific version of a package
dotnet add package Newtonsoft.Json --version 13.0.3
# Update an existing package
dotnet add package Serilog.AspNetCore
# List all installed packages and check for security vulnerabilities
dotnet list package --vulnerable --include-transitive
# Check for outdated packages with newer versions available
dotnet list package --outdated
# Remove a dependency
dotnet remove package Newtonsoft.Json
2. Central Package Management (CPM)
In enterprise repositories with dozens of projects, managing versions individually inside every .csproj leads to version drift, diamond dependency conflicts, and security vulnerabilities.
.NET provides Central Package Management (CPM). You define package versions once in a single Directory.Packages.props file at the repository root:
<!-- Directory.Packages.props at repository root -->
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
<ItemGroup>
<!-- Define centralized versions for all projects -->
<PackageVersion Include="MediatR" Version="12.2.0" />
<PackageVersion Include="FluentValidation" Version="11.9.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageVersion Include="xunit" Version="2.6.3" />
</ItemGroup>
</Project>
Now, individual .csproj files omit the version attribute entirely:
<!-- In src/OrdersApi/OrdersApi.csproj -->
<ItemGroup>
<!-- Version is centrally enforced from Directory.Packages.props -->
<PackageReference Include="MediatR" />
<PackageReference Include="FluentValidation" />
</ItemGroup>
3. Best Practices for Production Dependencies
- Always run vulnerability scans in CI/CD pipelines using
dotnet list package --vulnerable. - Lock dependency files using
packages.lock.json(<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>) to guarantee repeatable, deterministic builds across development and production servers.