csharp-patterns
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "csharp-patterns" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-f91c1bd5cea403734f3ffb48386281035db8bcdc842cb6ef1f8639b9a96e0271. Verify the upstream source and version against https://github.com/softspark/ai-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
C#/.NET patterns collection: covers common usages and examples for LINQ, async/await, dependency injection (DI), record types, nullable reference types, ASP.NET Core, Entity Framework Core, and MediatR. Trigger keywords: C#, .NET, dotnet, ASP.NET, EF Core, LINQ, record type, IServiceCollection.
Introduction source: third_party · softspark · 0.0.1 Reference
SkillPi interpretation
- Tasks
- 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.
- Testing
- Not tested
Browse files
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: ReadC# / .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 voidoutside event handlers -- always returnTask- Blocking with
.Result/.Wait()-- deadlock risk - Missing
CancellationTokenpropagation through the call chain - Catching bare
Exceptionwithout re-throw or structured logging - Service locator via
IServiceProvider.GetServicein business logic - Exposing
IQueryablefrom repositories -- leaks persistence details - Public setters on domain entities -- use methods + private setters
- String concatenation in hot paths -- use
StringBuilderor string handlers
Version history
-
v6.2.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
Original release notes
## 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
-
v5.5.0
GitHub ↗
Original release notes
### 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
-
v5.4.2
GitHub ↗
Original release notes
## 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
Only the five most recent versions are shown. View full version history at the source ↗
Current listing version
0.0.1
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供完整的 C#/.NET 全栈开发工程化模板
- 覆盖 LINQ、async/await、DI、records、nullable refs 等现代 C# 特性
- 集成 MediatR、EF Core、Polly、MassTransit 等主流框架最佳实践
- 包含测试策略(xUnit/NSubstitute/FluentAssertions)与 CI/CD 配置
Highlights
- 触发词完整覆盖 C#/.NET 生态核心关键词
- 边界清晰,无歧义或重叠风险
Areas to improve
-
缺少 When to Use 显式章节 Reported severity: Minor
文档未设置独立的 When to Use 章节说明适用场景
Recommendation: 建议在 frontmatter 后添加 When to Use 章节,明确说明本 Skill 适用于 .NET 后端开发、微服务架构、CQRS 模式等场景
Highlights
- 结构清晰,按开发流程组织内容
- 每节含可执行代码示例,便于直接复用
- frontmatter 完整,单文件长度合理
Highlights
- 代码示例语法正确,依赖版本明确
- 错误处理完善(ValidationBehavior、Result 模式)
- 资源管理可靠(IAsyncDisposable、CancellationToken 传播)
- 工具链完整(dotnet CLI、Testcontainers、BenchmarkDotNet)
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- api.payments.com
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.