csharp-patterns

C#/.NET 模式集合:涵盖 LINQ、async/await 异步模型、依赖注入(DI)、记录类型(records)、可空引用类型(nullable refs)、ASP.NET Core、Entity Framework Core 以及 MediatR 的常见用法与示例。触发关键词包括 C#、.NET、dotnet、ASP.NET、EF Core、LINQ、记录类型、IServiceCollection。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "csharp-patterns":https://skillpi.com/zh/skills/deepskill-f91c1bd5cea403734f3ffb48386281035db8bcdc842cb6ef1f8639b9a96e0271。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

C#/.NET 模式集合:涵盖 LINQ、async/await 异步模型、依赖注入(DI)、记录类型(records)、可空引用类型(nullable refs)、ASP.NET Core、Entity Framework Core 以及 MediatR 的常见用法与示例。触发关键词包括 C#、.NET、dotnet、ASP.NET、EF Core、LINQ、记录类型、IServiceCollection。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: csharp-patterns
description: "C#/.NET: LINQ, async/await, DI, records, nullable refs, ASP.NET Core, EF Core, MediatR. Triggers: C#, .NET, dotnet, ASP.NET, EF Core, LINQ, record type, IServiceCollection."
effort: medium
user-invocable: false
allowed-tools: Read

C# / .NET Patterns

Project Structure

Solution Layout

MyApp.sln
Directory.Build.props              # Shared build properties
Directory.Packages.props           # Central package management
src/
  MyApp.Api/                       # ASP.NET Core host (Controllers, Middleware, Program.cs)
  MyApp.Application/               # Use cases, MediatR handlers, Behaviors
  MyApp.Domain/                    # Entities, value objects, domain events
  MyApp.Infrastructure/            # EF Core, external services
tests/
  MyApp.UnitTests/
  MyApp.IntegrationTests/

Directory.Build.props

<Project>
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
  </PropertyGroup>
</Project>

Central Package Management (Directory.Packages.props)

<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
  </PropertyGroup>
  <ItemGroup>
    <PackageVersion Include="MediatR" Version="12.4.1" />
    <PackageVersion Include="FluentValidation" Version="11.11.0" />
    <PackageVersion Include="Microsoft.EntityFrameworkCore" Version="9.0.0" />
  </ItemGroup>
</Project>

Idioms / Code Style

Nullable Reference Types

public class Order
{
    public required string Id { get; init; }
    public string? Notes { get; set; }               // explicitly nullable
    public required Customer Customer { get; init; }  // never null
    public string Summary => $"Order {Id}: {Notes ?? "no notes"}";
}

Records

public record Money(decimal Amount, string Currency)
{
    public Money Add(Money other) => Currency != other.Currency
        ? throw new InvalidOperationException("Currency mismatch")
        : this with { Amount = Amount + other.Amount };
}

public record CreateOrderRequest(string CustomerId, List<OrderLineDto> Lines);
public record OrderLineDto(string ProductId, int Quantity);

Pattern Matching

public decimal CalculateDiscount(Customer c) => c switch
{
    { Tier: CustomerTier.Gold, TotalSpent: > 10_000m } => 0.20m,
    { Tier: CustomerTier.Gold }                        => 0.15m,
    { Tier: CustomerTier.Silver }                      => 0.10m,
    { IsNewCustomer: true }                            => 0.05m,
    _                                                  => 0m
};

// List patterns (.NET 8+)
public string Describe(int[] v) => v switch
{
    [] => "empty", [var x] => $"one: {x}", [var f, .., var l] => $"{f}..{l}",
};

LINQ

var activeUsers = users
    .Where(u => u.IsActive)
    .OrderByDescending(u => u.LastLogin)
    .Select(u => new UserDto(u.Id, u.Name))
    .ToList();

Async/Await

// Always: Async suffix, CancellationToken parameter, never .Result/.Wait()
public async Task<Order?> GetOrderAsync(string id, CancellationToken ct = default)
    => await _db.Orders.Include(o => o.Lines).FirstOrDefaultAsync(o => o.Id == id, ct);

// Parallel independent tasks
var ordersTask = _orderRepo.GetRecentAsync(ct);
var statsTask = _statsService.ComputeAsync(ct);
await Task.WhenAll(ordersTask, statsTask);

Primary Constructors (C# 12)

public class OrderService(IOrderRepository repo, ILogger<OrderService> logger, IPublisher pub)
{
    public async Task<Order> CreateAsync(CreateOrderRequest req, CancellationToken ct)
    {
        logger.LogInformation("Creating order for {CustomerId}", req.CustomerId);
        var order = Order.Create(req);
        await repo.AddAsync(order, ct);
        await pub.Publish(new OrderCreatedEvent(order.Id), ct);
        return order;
    }
}

Error Handling

Result Pattern

public sealed class Result<T>
{
    public T? Value { get; }
    public Error? Error { get; }
    public bool IsSuccess => Error is null;
    private Result(T value) => Value = value;
    private Result(Error error) => Error = error;
    public static Result<T> Success(T value) => new(value);
    public static Result<T> Failure(Error error) => new(error);
    public TOut Match<TOut>(Func<T, TOut> ok, Func<Error, TOut> err) =>
        IsSuccess ? ok(Value!) : err(Error!);
}
public record Error(string Code, string Message);

FluentValidation + MediatR Pipeline

public class CreateOrderValidator : AbstractValidator<CreateOrderRequest>
{
    public CreateOrderValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty().MaximumLength(36);
        RuleForEach(x => x.Lines).ChildRules(line =>
        {
            line.RuleFor(l => l.ProductId).NotEmpty();
            line.RuleFor(l => l.Quantity).GreaterThan(0).LessThanOrEqualTo(1000);
        });
    }
}

public class ValidationBehavior<TReq, TRes>(IEnumerable<IValidator<TReq>> validators)
    : IPipelineBehavior<TReq, TRes> where TReq : IRequest<TRes>
{
    public async Task<TRes> Handle(TReq req, RequestHandlerDelegate<TRes> next, CancellationToken ct)
    {
        var failures = validators.Select(v => v.Validate(req)).SelectMany(r => r.Errors).ToList();
        return failures.Count > 0 ? throw new ValidationException(failures) : await next();
    }
}

IAsyncDisposable

public sealed class TempFileHandle(string path) : IAsyncDisposable
{
    public async ValueTask DisposeAsync()
    {
        if (File.Exists(path)) await Task.Run(() => File.Delete(path));
    }
}
// Usage: await using var handle = new TempFileHandle("/tmp/export.csv");

Testing Patterns

xUnit + NSubstitute + FluentAssertions

public class OrderServiceTests
{
    private readonly IOrderRepository _repo = Substitute.For<IOrderRepository>();
    private readonly IPublisher _pub = Substitute.For<IPublisher>();
    private readonly OrderService _sut;
    public OrderServiceTests() => _sut = new(_repo, Substitute.For<ILogger<OrderService>>(), _pub);

    [Fact]
    public async Task CreateAsync_ValidRequest_ReturnsOrder()
    {
        var order = await _sut.CreateAsync(new("cust-1", [new("prod-1", 2)]), CancellationToken.None);
        order.Should().NotBeNull();
        order.Lines.Should().ContainSingle().Which.Quantity.Should().Be(2);
        await _repo.Received(1).AddAsync(Arg.Any<Order>(), Arg.Any<CancellationToken>());
    }

    [Theory]
    [InlineData(0)]
    [InlineData(-1)]
    public async Task CreateAsync_InvalidQuantity_Throws(int qty)
    {
        var act = () => _sut.CreateAsync(new("cust-1", [new("prod-1", qty)]), CancellationToken.None);
        await act.Should().ThrowAsync<ValidationException>();
    }
}

WebApplicationFactory (Integration)

public class OrdersApiTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task PostOrder_Returns201()
    {
        var client = factory.WithWebHostBuilder(b => b.ConfigureServices(s =>
        {
            s.RemoveAll<DbContext>();
            s.AddDbContext<AppDbContext>(o => o.UseInMemoryDatabase("test"));
        })).CreateClient();

        var response = await client.PostAsJsonAsync("/api/orders",
            new { CustomerId = "cust-1", Lines = new[] { new { ProductId = "prod-1", Quantity = 2 } } });
        response.StatusCode.Should().Be(HttpStatusCode.Created);
    }
}

Testcontainers

public class PostgresFixture : IAsyncLifetime
{
    private readonly PostgreSqlContainer _pg = new PostgreSqlBuilder().WithDatabase("testdb").Build();
    public string ConnectionString => _pg.GetConnectionString();
    public Task InitializeAsync() => _pg.StartAsync();
    public Task DisposeAsync() => _pg.DisposeAsync().AsTask();
}

Common Frameworks

ASP.NET Core Minimal API

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
var app = builder.Build();

app.MapGet("/api/orders/{id}", async (string id, ISender sender, CancellationToken ct) =>
    await sender.Send(new GetOrderQuery(id), ct) is { } order ? Results.Ok(order) : Results.NotFound());

app.MapPost("/api/orders", async (CreateOrderRequest req, ISender sender, CancellationToken ct) =>
    (await sender.Send(new CreateOrderCommand(req), ct)).Match(
        o => Results.Created($"/api/orders/{o.Id}", o),
        e => Results.Problem(e.Message, statusCode: 400)));
app.Run();

Entity Framework Core

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    protected override void OnModelCreating(ModelBuilder mb)
    {
        mb.Entity<Order>(b =>
        {
            b.HasKey(o => o.Id);
            b.Property(o => o.Id).HasMaxLength(36);
            b.HasMany(o => o.Lines).WithOne().HasForeignKey(l => l.OrderId);
            b.HasIndex(o => o.CustomerId);
            b.Property(o => o.Total).HasPrecision(18, 2);
        });
        mb.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
    }
}

MediatR (CQRS)

public record CreateOrderCommand(CreateOrderRequest Request) : IRequest<Result<Order>>;

public class CreateOrderHandler(IOrderRepository repo, IPublisher pub)
    : IRequestHandler<CreateOrderCommand, Result<Order>>
{
    public async Task<Result<Order>> Handle(CreateOrderCommand cmd, CancellationToken ct)
    {
        var order = Order.Create(cmd.Request);
        await repo.AddAsync(order, ct);
        await pub.Publish(new OrderCreatedEvent(order.Id), ct);
        return Result<Order>.Success(order);
    }
}

Polly (Resilience)

builder.Services.AddHttpClient("Payments", c => c.BaseAddress = new Uri("https://api.payments.com"))
.AddResilienceHandler("default", p =>
{
    p.AddRetry(new() { MaxRetryAttempts = 3, Delay = TimeSpan.FromMilliseconds(500),
        BackoffType = DelayBackoffType.Exponential,
        ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
            .HandleResult(r => r.StatusCode >= HttpStatusCode.InternalServerError) });
    p.AddCircuitBreaker(new() { FailureRatio = 0.5, SamplingDuration = TimeSpan.FromSeconds(30),
        BreakDuration = TimeSpan.FromSeconds(15) });
    p.AddTimeout(TimeSpan.FromSeconds(5));
});

MassTransit (Messaging)

builder.Services.AddMassTransit(x =>
{
    x.AddConsumer<OrderCreatedConsumer>();
    x.UsingRabbitMq((ctx, cfg) => { cfg.Host("rabbitmq://localhost"); cfg.ConfigureEndpoints(ctx); });
});

Performance Tips

Span<T> -- Zero-Allocation Parsing

public static ReadOnlySpan<char> ExtractDomain(ReadOnlySpan<char> email)
{
    int at = email.IndexOf('@');
    return at >= 0 ? email[(at + 1)..] : ReadOnlySpan<char>.Empty;
}
// Stack-allocated buffer: Span<byte> buf = stackalloc byte[256];

ValueTask -- Cache-Hit Fast Path

public ValueTask<Product?> GetProductAsync(string id, CancellationToken ct)
{
    if (_cache.TryGetValue(id, out var cached)) return ValueTask.FromResult<Product?>(cached);
    return new ValueTask<Product?>(LoadFromDbAsync(id, ct));
}

Source Generators

// JSON -- avoids runtime reflection
[JsonSerializable(typeof(Order))]
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
public partial class AppJsonContext : JsonSerializerContext;

// Logging -- avoids boxing
public static partial class Log
{
    [LoggerMessage(Level = LogLevel.Information, Message = "Order {OrderId} created")]
    public static partial void OrderCreated(ILogger logger, string orderId);
}

BenchmarkDotNet

[MemoryDiagnoser, SimpleJob(RuntimeMoniker.Net90)]
public class ParsingBenchmarks
{
    private readonly string _email = "user@example.com";
    [Benchmark(Baseline = true)] public string Sub() => _email[(_email.IndexOf('@') + 1)..];
    [Benchmark] public ReadOnlySpan<char> Span() => ExtractDomain(_email.AsSpan());
}
// dotnet run -c Release --project Benchmarks

Build / Package Management

dotnet CLI

dotnet new sln -n MyApp && dotnet new webapi -n MyApp.Api -o src/MyApp.Api
dotnet build -c Release
dotnet test -c Release --collect:"XPlat Code Coverage"
dotnet publish src/MyApp.Api -c Release -o ./publish
dotnet ef migrations add Init --project src/MyApp.Infrastructure --startup-project src/MyApp.Api

.editorconfig

[*.cs]
dotnet_sort_system_directives_first = true
csharp_style_namespace_declarations = file_scoped:error
csharp_prefer_primary_constructors = true:suggestion
dotnet_diagnostic.CA1848.severity = warning

CI (GitHub Actions)

steps:
  - uses: actions/checkout@v6
  - uses: actions/setup-dotnet@v4
    with: { dotnet-version: '9.0.x' }
  - run: dotnet restore
  - run: dotnet build --no-restore -c Release -warnaserror
  - run: dotnet test --no-build -c Release --collect:"XPlat Code Coverage"
  - run: dotnet publish src/MyApp.Api -c Release -o publish --no-build

Dockerfile

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish src/MyApp.Api -c Release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:9.0
COPY --from=build /app /app
WORKDIR /app
ENTRYPOINT ["dotnet", "MyApp.Api.dll"]

Anti-Patterns

  • async void outside event handlers -- always return Task
  • Blocking with .Result / .Wait() -- deadlock risk
  • Missing CancellationToken propagation through the call chain
  • Catching bare Exception without re-throw or structured logging
  • Service locator via IServiceProvider.GetService in business logic
  • Exposing IQueryable from repositories -- leaks persistence details
  • Public setters on domain entities -- use methods + private setters
  • String concatenation in hot paths -- use StringBuilder or string handlers

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 提供完整的 C#/.NET 全栈开发工程化模板
  • 覆盖 LINQ、async/await、DI、records、nullable refs 等现代 C# 特性
  • 集成 MediatR、EF Core、Polly、MassTransit 等主流框架最佳实践
  • 包含测试策略(xUnit/NSubstitute/FluentAssertions)与 CI/CD 配置
触发精准95/100

亮点

  • 触发词完整覆盖 C#/.NET 生态核心关键词
  • 边界清晰,无歧义或重叠风险
结构规范93/100

待提升项

  • 缺少 When to Use 显式章节 原报告严重程度:轻微

    文档未设置独立的 When to Use 章节说明适用场景

    改进建议:建议在 frontmatter 后添加 When to Use 章节,明确说明本 Skill 适用于 .NET 后端开发、微服务架构、CQRS 模式等场景

亮点

  • 结构清晰,按开发流程组织内容
  • 每节含可执行代码示例,便于直接复用
  • frontmatter 完整,单文件长度合理
执行可靠91/100

亮点

  • 代码示例语法正确,依赖版本明确
  • 错误处理完善(ValidationBehavior、Result 模式)
  • 资源管理可靠(IAsyncDisposable、CancellationToken 传播)
  • 工具链完整(dotnet CLI、Testcontainers、BenchmarkDotNet)
证据可验 (前四项均值)93/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • api.payments.com

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。