Community编程与开发github.com

dotnet-project-structure

现代 .NET 项目结构,包含 .slnx 解决方案格式、Directory.Build.props、中央包管理、SourceLink、基于 RELEASE_NOTES.md 的版本管理和 global.json 的 SDK 锁定。

dotnet-project-structure 是什么?

该技能为 .NET 开发人员和 AI 代理(如 Claude Code、Cursor 或 Codex)提供了设置现代 .NET 项目结构所需的所有知识。它涵盖了如何创建和迁移到 .slnx 解决方案格式,该格式通过标准 XML 提高了可读性和合并体验。此外,还详细介绍了通过 Directory.Build.props 进行集中构建配置、通过 Directory.Packages.props 实现中央包管理(CPM)、使用 SourceLink 实现 NuGet 包的可调试性、通过 global.json 锁定 .NET SDK 版本,以及使用 RELEASE_NOTES.md 进行自动化版本管理。该技能支持 .NET SDK 9.0.200+ 和 Visual Studio 17.13+,并提供了清晰的脚本示例来解析发布说明和更新版本,从而实现高效的 CI/CD 流水线,可用于 NuGet 发布、代码审查和团队协作。

兼容平台~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 解决方案
  • 在多个项目之间配置集中式生成属性
  • 实现中央包版本管理
  • 设置 SourceLink 以支持调试和 NuGet 包
  • 使用发布说明自动化版本管理
  • 锁定 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 格式一致
  • 在拉取请求中获得更好的差异/审查体验

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 "Updated to version $($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        # 中央包版本管理
├── global.json                     # SDK 版本锁定
├── MySolution.slnx                 # 现代解决方案文件
├── NuGet.Config                    # NuGet 源配置
├── README.md                       # 项目文档
├── RELEASE_NOTES.md                # 发布说明
└── logo.png                        # NuGet 包图标

快速设置指南

在 .NET 9+ 中启动新项目:

# 1. 创建解决方案和项目
dotnet new sln --name MySolution --format slnx
dotnet new console -o src/MyApp
dotnet new xunit -o tests/MyApp.Tests
dotnet sln add src/MyApp/MyApp.csproj
dotnet sln add tests/MyApp.Tests/MyApp.Tests.csproj

# 2. 创建配置文件
# 创建 Directory.Build.props、Directory.Packages.props、
# global.json 和 NuGet.Config(参见上方的完整示例)

# 3. 设置发布说明
echo "#### 1.0.0 $(Get-Date -Format 'MMMM dd yyyy') ####" > RELEASE_NOTES.md

# 4. 生成并测试
dotnet build
dotnet test

此设置为您提供了一个生产就绪的 .NET 项目,具有现代结构、版本管理和可调试的包。

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.

相关技能