Community程式設計與開發github.com

dotnet-project-structure

現代化的 .NET 專案結構,包含 .slnx 解決方案格式、Directory.Build.props、集中式套件管理、SourceLink、使用 RELEASE_NOTES.md 的版本管理,以及透過 global.json 進行的 SDK 釘選。

dotnet-project-structure 是什麼?

此技能提供一套完整的現代化 .NET 專案結構與建置配置最佳實踐。它涵蓋了從解決方案檔案格式的選擇,到集中式建置屬性與套件版本管理的完整方案。核心重點包括推廣使用 .NET 9 引入的 XML 格式 .slnx,以取代傳統的 .sln 格式,獲得更好的可讀性、版本控制差異比較與合併體驗。此外,透過 `Directory.Build.props` 集中管理所有專案的語言設定、中繼資料、SourceLink 除錯支援與動態版權年份;利用 `Directory.Packages.props` 實現集中式套件管理 (CPM),避免版本漂移;並透過 `global.json` 釘選 .NET SDK 版本以確保全環境建置一致性。此技能也整合了以 `RELEASE_NOTES.md` 為基礎的版本管理流程,並提供 PowerShell 指令碼來自動解析版本資訊並更新建置檔案,適合使用 .NET 9 或更新版本的開發團隊,在 Visual Studio 2022 (17.13+) 或命令列環境中運作。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/project-structure

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

.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 SDK9.0.200
Visual Studio17.13
MSBuildVisual 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 中遷移:

  1. 開啟解決方案
  2. 在方案總管中選取解決方案
  3. 前往 檔案 > 另存解決方案...
  4. 將「存檔類型」變更為 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>

優點

  1. 單一事實來源 - 所有版本集中在一個檔案中
  2. 無版本漂移 - 所有專案使用相同版本
  3. 易於更新 - 只需變更一次,套用到所有地方
  4. 分組套件 - 為相關套組使用版本變數 (例如所有 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                        # 套件圖示

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-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.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能