Community程式設計與開發github.com

套件管理

使用 Central Package Management (CPM) 和 dotnet CLI 命令管理 NuGet 套件。切勿直接編輯 XML——應使用 dotnet add/remove/list 命令。針對相關套件使用共享版本變數。

套件管理 是什麼?

此技能提供了一套全面的 NuGet 套件管理方法,特別著重於 .NET 生態系統中的 Central Package Management (CPM)。其核心原則為「絕不直接編輯 XML」——所有套件操作(新增、移除、更新)都必須透過 dotnet CLI 命令執行,因為 CLI 會自動驗證套件是否存在、正確解析版本、處理傳遞性相依性,並在啟用時更新鎖定檔案。技能詳細說明了 CPM 的啟用方式、如何使用共享版本變數來群組管理相關套件(例如 Akka.NET 或 OpenTelemetry),以及何時不適合使用 CPM(例如舊版專案、需要版本範圍、或使用較舊的 .NET SDK)。此外,它也涵蓋了常見的 CLI 命令參考、套件來源設定、開發專用或條件式套件的常見模式,以及疑難排解和反模式。本技能支援所有使用 .NET SDK 和 NuGet 的開發環境(如 Visual Studio、VS Code、JetBrains Rider),並且能與 `dotnet/slopwatch` 等技能協同運作,以偵測潛在的程式碼混亂。

相容平台~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 套件
  • 為解決方案設定 Central Package Management (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 正確搭配使用

Central Package Management (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

Central Package Management 並非總是正確選擇:

舊版專案

將現有的大型解決方案遷移至 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 將無幫助——每個存放庫都需要自己的設定。


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 <名稱>
新增特定版本dotnet add package <名稱> --version <版本>
移除套件dotnet remove package <名稱>
列出套件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.

相關技能