Community编程与开发github.com

NuGet 包管理

使用集中式包管理(CPM)和 dotnet CLI 命令管理 NuGet 包。永远不要直接编辑 XML——使用 dotnet add/remove/list 命令。为相关包使用共享版本变量。

NuGet 包管理 是什么?

该技能提供了一套完整的 NuGet 包管理指南,特别针对 .NET 开发者,强调使用 dotnet CLI 命令而非手动编辑 XML 文件,以确保包依赖的准确性和可维护性。它详细介绍了如何启用和使用集中式包管理(CPM),通过单一的 `Directory.Packages.props` 文件集中管理所有项目中的包版本,从而消除版本冲突。此外,技能还引入了共享版本变量的概念,允许将相关包(如 Akka.NET、Aspire、OpenTelemetry)分组,并通过一个变量统一更新版本号,极大简化了维护工作。该技能支持 Cursor、Claude Code 等 AI 编码助手,也适用于任何 .NET 开发环境。它涵盖了包添加、移除、列表、更新、恢复等常见 CLI 命令,以及包源配置、条件包引用、版本覆盖等高级模式和故障排除技巧,帮助开发者避免反模式,确保项目依赖的健壮性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/package-management

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

NuGet 包管理 是做什么的?

何时使用此技能

在以下情况下使用此技能:

  • 添加、移除或更新 NuGet 包
  • 为解决方案设置集中式包管理 (CPM)
  • 管理多个项目中的包版本
  • 解决包冲突或还原问题

黄金法则:永远不要直接编辑 XML

始终使用 dotnet CLI 命令来管理包。 永远不要手动编辑 .csproj 或 Directory.Packages.props 文件。

# 正确做法:使用 CLI 命令
dotnet add package Newtonsoft.Json
dotnet remove package Newtonsoft.Json
dotnet list package --outdated

# 错误做法:直接编辑 XML
# <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />

原因:

  • CLI 会验证包是否存在并解析正确的版本
  • 正确处理传递性依赖
  • 更新锁文件(如果存在)
  • 避免拼写错误和格式错误的 XML
  • 与 CPM 正确配合

集中式包管理 (CPM)

CPM 将所有包版本集中在一个文件中,消除了跨项目的版本冲突。

启用 CPM

在解决方案根目录创建 Directory.Packages.props:

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

  <ItemGroup>
    <PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageVersion Include="Serilog" Version="4.0.0" />
    <PackageVersion Include="xunit" Version="2.9.2" />
  </ItemGroup>
</Project>

使用 CPM 的项目文件

项目引用包时不带版本:

<!-- src/MyApp/MyApp.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" />
    <PackageReference Include="Serilog" />
  </ItemGroup>
</Project>

使用 CPM 添加包

# 同时添加到 Directory.Packages.props 和项目文件
dotnet add package Serilog.Sinks.Console

# 在 Directory.Packages.props 中的结果:
# <PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />

# 在项目文件中的结果:
# <PackageReference Include="Serilog.Sinks.Console" />

共享版本变量

使用共享版本变量将相关包分组:

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

  <!-- 共享版本变量 -->
  <PropertyGroup Label="SharedVersions">
    <AkkaVersion>1.5.59</AkkaVersion>
    <AkkaHostingVersion>1.5.59</AkkaHostingVersion>
    <AspireVersion>9.0.0</AspireVersion>
    <OpenTelemetryVersion>1.11.0</OpenTelemetryVersion>
    <XunitVersion>2.9.2</XunitVersion>
  </PropertyGroup>

  <!-- Akka.NET 包 - 全部使用相同版本 -->
  <ItemGroup Label="Akka.NET">
    <PackageVersion Include="Akka" Version="$(AkkaVersion)" />
    <PackageVersion Include="Akka.Cluster" Version="$(AkkaVersion)" />
    <PackageVersion Include="Akka.Cluster.Sharding" Version="$(AkkaVersion)" />
    <PackageVersion Include="Akka.Cluster.Tools" Version="$(AkkaVersion)" />
    <PackageVersion Include="Akka.Persistence" Version="$(AkkaVersion)" />
    <PackageVersion Include="Akka.Streams" Version="$(AkkaVersion)" />
    <PackageVersion Include="Akka.Hosting" Version="$(AkkaHostingVersion)" />
    <PackageVersion Include="Akka.Cluster.Hosting" Version="$(AkkaHostingVersion)" />
  </ItemGroup>

  <!-- Aspire 包 -->
  <ItemGroup Label="Aspire">
    <PackageVersion Include="Aspire.Hosting" Version="$(AspireVersion)" />
    <PackageVersion Include="Aspire.Hosting.AppHost" Version="$(AspireVersion)" />
    <PackageVersion Include="Aspire.Hosting.PostgreSQL" Version="$(AspireVersion)" />
    <PackageVersion Include="Aspire.Hosting.Testing" Version="$(AspireVersion)" />
  </ItemGroup>

  <!-- OpenTelemetry 包 -->
  <ItemGroup Label="OpenTelemetry">
    <PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="$(OpenTelemetryVersion)" />
    <PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="$(OpenTelemetryVersion)" />
    <PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="$(OpenTelemetryVersion)" />
    <PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="$(OpenTelemetryVersion)" />
  </ItemGroup>

  <!-- 测试 -->
  <ItemGroup Label="Testing">
    <PackageVersion Include="xunit" Version="$(XunitVersion)" />
    <PackageVersion Include="xunit.runner.visualstudio" Version="$(XunitVersion)" />
    <PackageVersion Include="FluentAssertions" Version="6.12.0" />
    <PackageVersion Include="Verify.Xunit" Version="26.0.0" />
  </ItemGroup>
</Project>

优点:

  • 通过更改一个变量即可更新所有 Akka 包
  • 使用带标签的 ItemGroup 清晰组织
  • 防止相关包的版本不匹配

何时不使用 CPM

集中式包管理并非总是正确的选择:

遗留项目

将现有的庞大解决方案迁移到 CPM 可能会引入问题:

  • 现有的版本冲突会同时暴露出来
  • 某些包可能故意有不同的版本
  • 迁移需要同时修改大量文件

建议:对于遗留项目,请增量迁移,或者如果当前方式运行良好,则坚持使用每个项目单独版本。

版本范围

CPM 需要精确版本——不支持版本范围:

<!-- CPM 不支持 -->
<PackageVersion Include="Newtonsoft.Json" Version="[13.0,14.0)" />

<!-- 必须使用精确版本 -->
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />

如果你需要版本范围(虽然罕见,但某些库场景需要),CPM 将无法工作。

较旧的 .NET 版本

CPM 要求:

  • .NET SDK 6.0.300+ 或更高版本
  • NuGet 6.2+ 或更高版本
  • Visual Studio 2022 17.2+ 或更高版本

如果你针对较旧的 SDK 版本,或者团队成员使用较旧工具,CPM 可能会导致构建失败。

多仓库解决方案

如果你的解决方案跨越多个独立构建的仓库,CPM 的单一 Directory.Packages.props 文件将无济于事——每个仓库都需要自己的 CPM 配置。


CLI 命令参考

添加包

# 添加最新的稳定版本
dotnet add package Serilog

# 添加特定版本
dotnet add package Serilog --version 4.0.0

# 添加预发布版本
dotnet add package Serilog --prerelease

# 添加到特定项目
dotnet add src/MyApp/MyApp.csproj package Serilog

移除包

# 从当前项目移除
dotnet remove package Serilog

# 从特定项目移除
dotnet remove src/MyApp/MyApp.csproj package Serilog

列出包

# 列出解决方案中的所有包
dotnet list package

# 显示过时的包
dotnet list package --outdated

# 包含传递性依赖
dotnet list package --include-transitive

# 显示有漏洞的包
dotnet list package --vulnerable

# 显示已弃用的包
dotnet list package --deprecated

更新包

# 使用 CPM:在 Directory.Packages.props 中编辑版本
# 然后还原以应用更改
dotnet restore

# 不使用 CPM:移除并添加新版本
dotnet remove package Serilog
dotnet add package Serilog --version 4.1.0

# 或者使用 dotnet-outdated 工具(推荐)
dotnet tool install --global dotnet-outdated-tool
dotnet outdated --upgrade

还原和清理

# 还原包
dotnet restore

# 清除本地缓存(故障排除)
dotnet nuget locals all --clear

# 强制还原(忽略缓存)
dotnet restore --force

包源

列出源

dotnet nuget list source

添加私有源

# 添加经过身份验证的源
dotnet nuget add source https://pkgs.dev.azure.com/myorg/_packaging/myfeed/nuget/v3/index.json \
  --name MyFeed \
  --username az \
  --password $PAT \
  --store-password-in-clear-text

NuGet.config

对于解决方案特定的源,创建 NuGet.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="MyPrivateFeed" value="https://pkgs.dev.azure.com/myorg/_packaging/myfeed/nuget/v3/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <MyPrivateFeed>
      <add key="Username" value="az" />
      <add key="ClearTextPassword" value="%NUGET_PAT%" />
    </MyPrivateFeed>
  </packageSourceCredentials>
</configuration>

常见模式

仅开发依赖包

<!-- Directory.Packages.props -->
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />

<!-- 项目文件 - 标记为开发依赖 -->
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" />

条件包

<!-- 仅在 Debug 构建中包含 -->
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
  <PackageReference Include="JetBrains.Annotations" />
</ItemGroup>

<!-- 平台特定 -->
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
  <PackageReference Include="System.Text.Json" />
</ItemGroup>

版本覆盖(逃生舱口)

当你必须为某个项目覆盖 CPM 时(很少见):

<!-- 项目文件 - 谨慎使用! -->
<PackageReference Include="Newtonsoft.Json" VersionOverride="12.0.3" />

警告:这会被 Slopwatch(参见 dotnet/slopwatch 技能)检测为潜在的垃圾代码。


故障排除

版本冲突

# 查看完整的依赖树
dotnet list package --include-transitive

# 查找哪些包引入了特定包
dotnet list package --include-transitive | grep -i "PackageName"

还原失败

# 清除所有缓存
dotnet nuget locals all --clear

# 使用详细日志还原
dotnet restore --verbosity detailed

# 检查锁定包
cat packages.lock.json

锁文件

为可重现的构建,请使用包锁文件:

<!-- Directory.Build.props -->
<PropertyGroup>
  <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
</PropertyGroup>

然后提交 packages.lock.json 文件。


反模式

不要:直接编辑 XML

<!-- 错误:手动编辑 XML -->
<PackageReference Include="Typo.Package" Version="1.0.0" />
<!-- 包可能不存在!CLI 会捕获这个问题。 -->

不要:在 CPM 中内联版本

<!-- 错误:绕过 CPM -->
<PackageReference Include="Serilog" Version="4.0.0" />

<!-- 正确:版本来自 Directory.Packages.props -->
<PackageReference Include="Serilog" />

不要:混合版本管理

<!-- 错误:部分版本在 CPM 中,部分内联 -->
<PackageReference Include="Serilog" />  <!-- 来自 CPM -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />  <!-- 内联 -->

不要:忘记共享变量

<!-- 错误:相关包使用不同版本 -->
<PackageVersion Include="Akka" Version="1.5.59" />
<PackageVersion Include="Akka.Cluster" Version="1.5.58" />  <!-- 不匹配! -->

<!-- 正确:使用共享变量 -->
<PackageVersion Include="Akka" Version="$(AkkaVersion)" />
<PackageVersion Include="Akka.Cluster" Version="$(AkkaVersion)" />

快速参考

任务命令
添加包dotnet add package <name>
添加特定版本dotnet add package <name> --version <ver>
移除包dotnet remove package <name>
列出包dotnet list package
显示过时的dotnet list package --outdated
显示有漏洞的dotnet list package --vulnerable
还原dotnet restore
清除缓存dotnet nuget locals all --clear

资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

相关技能