.NET 專案結構與建置配置
何時使用此技能
在以下情況使用此技能:
- 建立採用現代最佳實務的新 .NET 解決方案
- 跨多個專案集中設定建置屬性
- 實作集中式套件版本管理
- 為除錯和 NuGet 套件設定 SourceLink
- 使用版本發行說明自動化版本管理
- 為一致性的建置釘選 SDK 版本
相關技能
dotnet-local-tools- 使用 dotnet-tools.json 管理本機 .NET 工具microsoft-extensions-configuration- 設定驗證模式
解決方案檔案格式 (.slnx)
.slnx 格式是 .NET 9 引入的現代化 XML 解決方案檔案格式。它取代了傳統的 .sln 格式。
相較於傳統 .sln 的優點
| 面向 | .sln (舊版) | .slnx (現代) |
|---|---|---|
| 格式 | 自訂文字格式 | 標準 XML |
| 可讀性 | GUID、難以理解的語法 | 簡潔、人類可讀 |
| 版本控制 | 難以差異比較/合併 | 易於差異比較/合併 |
| 編輯 | 需要 IDE | 任何文字編輯器 |
版本需求
| 工具 | 最低版本 |
|---|---|
| .NET SDK | 9.0.200 |
| Visual Studio | 17.13 |
| MSBuild | Visual Studio Build Tools 17.13 |
注意: 從 .NET 10 開始,dotnet new sln 預設會建立 .slnx 檔案。在 .NET 9 中,您必須明確遷移或指定格式。
範例 .slnx 檔案
<Solution>
<Folder Name="/build/">
<File Path="Directory.Build.props" />
<File Path="Directory.Packages.props" />
<File Path="global.json" />
<File Path="NuGet.Config" />
<File Path="README.md" />
</Folder>
<Folder Name="/src/">
<Project Path="src/MyApp/MyApp.csproj" />
<Project Path="src/MyApp.Core/MyApp.Core.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/MyApp.Tests/MyApp.Tests.csproj" />
</Folder>
</Solution>
從 .sln 遷移到 .slnx
使用 dotnet sln migrate 命令來轉換現有解決方案:
# 遷移特定的解決方案檔案
dotnet sln MySolution.sln migrate
# 或者,如果目錄中只有一個 .sln 檔案,直接執行:
dotnet sln migrate
重要: 請勿在同一個儲存庫中同時保留 .sln 和 .slnx 檔案。這會導致自動解決方案偵測問題,並可能造成同步問題。遷移完成後,請刪除舊的 .sln 檔案。
您也可以在 Visual Studio 中遷移:
- 開啟解決方案
- 在方案總管中選取解決方案
- 前往 檔案 > 另存解決方案...
- 將「存檔類型」變更為 Xml 解決方案檔案 (*.slnx)
建立新的 .slnx 解決方案
# .NET 10+:預設建立 .slnx
dotnet new sln --name MySolution
# .NET 9:明確指定格式
dotnet new sln --name MySolution --format slnx
# 新增專案 (兩種格式的運作方式相同)
dotnet sln add src/MyApp/MyApp.csproj
建議
如果您使用的是 .NET 9.0.200 或更新版本,請將解決方案遷移到 .slnx。 好處非常顯著:
- 大幅減少合併衝突 (不再有隨機變更的 GUID)
- 人類可讀,可在任何文字編輯器中編輯
- 與現代的
.csproj格式一致 - 在 Pull Request 中有更好的差異比較/審查體驗
Directory.Build.props
Directory.Build.props 提供集中式建置配置,會套用至目錄樹中的所有專案。請將其放在解決方案根目錄。
完整範例
<Project>
<!-- 中繼資料 -->
<PropertyGroup>
<Authors>Your Team</Authors>
<Company>Your Company</Company>
<!-- 動態版權年份 - 自動更新 -->
<Copyright>Copyright © 2020-$([System.DateTime]::Now.Year) Your Company</Copyright>
<Product>Your Product</Product>
<PackageProjectUrl>https://github.com/yourorg/yourrepo</PackageProjectUrl>
<RepositoryUrl>https://github.com/yourorg/yourrepo</RepositoryUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<PackageTags>your;tags;here</PackageTags>
</PropertyGroup>
<!-- C# 語言設定 -->
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>$(NoWarn);CS1591</NoWarn> <!-- 遺漏的 XML 註解 -->
</PropertyGroup>
<!-- 版本管理 -->
<PropertyGroup>
<VersionPrefix>1.0.0</VersionPrefix>
<PackageReleaseNotes>See RELEASE_NOTES.md</PackageReleaseNotes>
</PropertyGroup>
<!-- 目標框架定義 (可重複使用的屬性) -->
<PropertyGroup>
<NetStandardLibVersion>netstandard2.0</NetStandardLibVersion>
<NetLibVersion>net8.0</NetLibVersion>
<NetTestVersion>net9.0</NetTestVersion>
</PropertyGroup>
<!-- SourceLink 配置 -->
<PropertyGroup>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" />
</ItemGroup>
<!-- NuGet 套件資源 -->
<ItemGroup>
<None Include="$(MSBuildThisFileDirectory)logo.png" Pack="true" PackagePath="\" />
<None Include="$(MSBuildThisFileDirectory)README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<PropertyGroup>
<PackageIcon>logo.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
</PropertyGroup>
<!-- 全域 using 陳述式 -->
<ItemGroup>
<Using Include="System.Collections.Immutable" />
</ItemGroup>
</Project>
關鍵模式
動態版權年份
<Copyright>Copyright © 2020-$([System.DateTime]::Now.Year) Your Company</Copyright>
使用 MSBuild 屬性函式在建置時插入當前年份。無需手動更新。
可重複使用的目標框架屬性
定義一次目標框架,到處參考:
<!-- 在 Directory.Build.props 中 -->
<PropertyGroup>
<NetLibVersion>net8.0</NetLibVersion>
<NetTestVersion>net9.0</NetTestVersion>
</PropertyGroup>
<!-- 在 MyApp.csproj 中 -->
<PropertyGroup>
<TargetFramework>$(NetLibVersion)</TargetFramework>
</PropertyGroup>
<!-- 在 MyApp.Tests.csproj 中 -->
<PropertyGroup>
<TargetFramework>$(NetTestVersion)</TargetFramework>
</PropertyGroup>
用於 NuGet 套件的 SourceLink
SourceLink 可以對 NuGet 套件進行逐步除錯:
<PropertyGroup>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<!-- 為您的原始檔控制選擇正確的提供者 -->
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" />
<!-- 或:Microsoft.SourceLink.AzureRepos.Git -->
<!-- 或:Microsoft.SourceLink.GitLab -->
<!-- 或:Microsoft.SourceLink.Bitbucket.Git -->
</ItemGroup>
Directory.Packages.props - 集中式套件管理
集中式套件管理 (CPM) 為所有 NuGet 套件版本提供單一事實來源。
設定
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<!-- 為相關套件定義版本變數 -->
<PropertyGroup>
<AkkaVersion>1.5.35</AkkaVersion>
<AspireVersion>9.1.0</AspireVersion>
</PropertyGroup>
<!-- 應用程式相依性 -->
<ItemGroup Label="App Dependencies">
<PackageVersion Include="Akka" Version="$(AkkaVersion)" />
<PackageVersion Include="Akka.Cluster" Version="$(AkkaVersion)" />
<PackageVersion Include="Akka.Persistence" Version="$(AkkaVersion)" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
</ItemGroup>
<!-- 建置/工具相依性 -->
<ItemGroup Label="Build Dependencies">
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />
</ItemGroup>
<!-- 測試相依性 -->
<ItemGroup Label="Test Dependencies">
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.0.1" />
<PackageVersion Include="FluentAssertions" Version="7.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="coverlet.collector" Version="6.0.3" />
</ItemGroup>
</Project>
取用套件 (無需指定版本)
<!-- 在 MyApp.csproj 中 -->
<ItemGroup>
<PackageReference Include="Akka" />
<PackageReference Include="Akka.Cluster" />
<PackageReference Include="Microsoft.Extensions.Hosting" />
</ItemGroup>
<!-- 在 MyApp.Tests.csproj 中 -->
<ItemGroup>
<PackageReference Include="xunit" />
<PackageReference Include="FluentAssertions" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
</ItemGroup>
優點
- 單一事實來源 - 所有版本集中在一個檔案中
- 無版本漂移 - 所有專案使用相同版本
- 易於更新 - 只需變更一次,套用到所有地方
- 分組套件 - 為相關套組使用版本變數 (例如所有 Akka 套件)
global.json - SDK 版本釘選
為確保跨所有環境的建置一致性,請釘選 .NET SDK 版本。
{
"sdk": {
"version": "9.0.200",
"rollForward": "latestFeature"
}
}
向前復原原則
| 原則 | 行為 |
|---|---|
disable | 要求完全相符的版本 |
patch | 相同主要.次要,最新的修補程式 |
feature | 相同主要,最新的次要.修補程式 |
latestFeature | 相同主要,最新的功能帶 |
minor | 相同主要,最新的次要 |
latestMinor | 相同主要,最新的次要 |
major | 最新 SDK (不建議使用) |
建議: latestFeature - 允許在同一功能帶內進行修補程式更新。
使用 RELEASE_NOTES.md 進行版本管理
版本發行說明格式
#### 1.2.0 January 15th 2025 ####
- 新增功能 X
- 修正 Y 中的錯誤
- 改善 Z 的效能
#### 1.1.0 December 10th 2024 ####
- 初始版本,包含功能 A、B、C
解析指令碼 (getReleaseNotes.ps1)
function Get-ReleaseNotes {
param (
[Parameter(Mandatory=$true)]
[string]$MarkdownFile
)
$content = Get-Content -Path $MarkdownFile -Raw
$sections = $content -split "####"
$result = [PSCustomObject]@{
Version = $null
Date = $null
ReleaseNotes = $null
}
if ($sections.Count -ge 3) {
$header = $sections[1].Trim()
$releaseNotes = $sections[2].Trim()
$headerParts = $header -split " ", 2
if ($headerParts.Count -eq 2) {
$result.Version = $headerParts[0]
$result.Date = $headerParts[1]
}
$result.ReleaseNotes = $releaseNotes
}
return $result
}
版本升級指令碼 (bumpVersion.ps1)
function UpdateVersionAndReleaseNotes {
param (
[Parameter(Mandatory=$true)]
[PSCustomObject]$ReleaseNotesResult,
[Parameter(Mandatory=$true)]
[string]$XmlFilePath
)
$xmlContent = New-Object XML
$xmlContent.Load($XmlFilePath)
# 更新 VersionPrefix
$versionElement = $xmlContent.SelectSingleNode("//VersionPrefix")
$versionElement.InnerText = $ReleaseNotesResult.Version
# 更新 PackageReleaseNotes
$notesElement = $xmlContent.SelectSingleNode("//PackageReleaseNotes")
$notesElement.InnerText = $ReleaseNotesResult.ReleaseNotes
$xmlContent.Save($XmlFilePath)
}
建置指令碼 (build.ps1)
# 載入輔助指令碼
. "$PSScriptRoot\scripts\getReleaseNotes.ps1"
. "$PSScriptRoot\scripts\bumpVersion.ps1"
# 解析版本發行說明並更新 Directory.Build.props
$releaseNotes = Get-ReleaseNotes -MarkdownFile (Join-Path -Path $PSScriptRoot -ChildPath "RELEASE_NOTES.md")
UpdateVersionAndReleaseNotes -ReleaseNotesResult $releaseNotes -XmlFilePath (Join-Path -Path $PSScriptRoot -ChildPath "Directory.Build.props")
Write-Output "已更新至版本 $($releaseNotes.Version)"
CI/CD 整合
# GitHub Actions 範例
- name: 從版本發行說明更新版本
shell: pwsh
run: ./build.ps1
- name: 建置
run: dotnet build -c Release
- name: 使用標籤版本進行封裝
run: dotnet pack -c Release /p:PackageVersion=${{ github.ref_name }}
- name: 推送至 NuGet
run: dotnet nuget push **/*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json
NuGet.Config
設定 NuGet 來源和行為:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
<!-- 如有需要,可新增私人摘要 -->
<!-- <add key="MyCompany" value="https://pkgs.dev.azure.com/myorg/_packaging/myfeed/nuget/v3/index.json" /> -->
</packageSources>
</configuration>
重要設定:
<clear />- 移除繼承/預設來源,以實現可重複的建置disableSourceControlIntegration- 防止 TFS/Git 整合問題
完整專案結構
MySolution/
├── .config/
│ └── dotnet-tools.json # 本機 .NET 工具
├── .github/
│ └── workflows/
│ ├── pr-validation.yml # PR 檢查
│ └── release.yml # NuGet 發佈
├── scripts/
│ ├── getReleaseNotes.ps1 # 解析 RELEASE_NOTES.md
│ └── bumpVersion.ps1 # 更新 Directory.Build.props
├── src/
│ ├── MyApp/
│ │ └── MyApp.csproj
│ └── MyApp.Core/
│ └── MyApp.Core.csproj
├── tests/
│ └── MyApp.Tests/
│ └── MyApp.Tests.csproj
├── Directory.Build.props # 集中式建置配置
├── Directory.Packages.props # 集中式套件版本管理
├── MySolution.slnx # 現代化解決方案檔案
├── global.json # SDK 版本釘選
├── NuGet.Config # NuGet 摘要配置
├── RELEASE_NOTES.md # 版本發行說明
├── README.md # 專案說明
└── logo.png # 套件圖示