Write production-grade C# and ASP.NET Core services on .NET 10 (with .NET 8 notes) — minimal APIs vs controllers, DI lifetimes, options and secrets, async/await with cancellation, nullable reference types, validation with AddValidation, ProblemDetails errors, EF Core usage, IHttpClientFactory with the standard resilience handler, structured logging, JWT and policy authorization, background services and built-in OpenAPI.
When agents use itUse this whenever the user asks to write, refactor, debug or explain C# back-end code; edits Program.cs, appsettings.json, a DbContext, entity configurations, controllers, endpoint mappings, middleware, hosted services or HttpClient registrations; hits a deadlock, ObjectDisposedException, "Cannot consume scoped service from singleton", nullable warnings; or asks "how do I do X in ASP.NET Core". Also use it when a Node or Java developer asks for the ASP.NET Core equivalent of a pattern. For tests use dotnet-testing; for slow or memory-hungry services use dotnet-performance.
Install
Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.
npx skills add AGCO-Global/org-skills --skill dotnet-development -a github-copilot
# or with the org installer (adds .github/skills/dotnet-development):
npx -y github:AGCO-Global/org-skills add skill dotnet-development
Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.
Installs the backend-dotnet-skills plugin, which bundles all Backend / .NET skills and keeps them updated.
/plugin marketplace add AGCO-Global/org-skills
/plugin install backend-dotnet-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill dotnet-development -a claude-code
Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.
Installs into .agents/skills/, which Codex reads.
npx skills add AGCO-Global/org-skills --skill dotnet-development -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill dotnet-development -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill dotnet-development -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the dotnet-development folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.
The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.
Write every service as if it runs under load, behind a load balancer, with requests cancelled mid-flight and configuration injected by the platform. Check the version first: read global.json, <TargetFramework> and Directory.Packages.props. Do not use keyed services or IExceptionHandler below .NET 8, AddOpenApi below .NET 9, or AddValidation and TypedResults.ServerSentEvents below .NET 10.
1. Decide first
Question
Default
Change when
Endpoint style
Minimal APIs: MapGroup per feature, TypedResults
A large controller codebase already exists → stay with [ApiController]; Native AOT → minimal APIs only
Validation
AddValidation() with DataAnnotations (.NET 10+)
Cross-field or async rules → FluentValidation; controllers → [ApiController] model validation. One mechanism per solution
Error shape
RFC 9457 ProblemDetails from AddProblemDetails()
Never a custom envelope
Data access
EF Core 10, scoped DbContext, projection to DTOs
Bulk or reporting SQL → SqlQuery<T> or Dapper next to EF
Outbound HTTP
Typed client + AddStandardResilienceHandler()
Non-idempotent calls → disable retries or send an idempotency key
Background work
BackgroundService + scope per iteration
Must survive restarts → broker or job library, see messaging-patterns
Caching shared data
HybridCache
Per-instance, tiny and static → IMemoryCache
2. Thin endpoints
Bind, validate, call one handler, map the result. No EF queries or business rules inside Program.cs lambdas.
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddValidation(); // .NET 10+
builder.Services.AddAuthentication().AddJwtBearer(); // reads Authentication:Schemes:Bearer
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseExceptionHandler(); // parameterless overload needs AddProblemDetails()
app.UseStatusCodePages();
var orders = app.MapGroup("/orders").WithTags("Orders").RequireAuthorization();
orders.MapGet("/{id:guid}", async Task<Results<Ok<OrderDto>, NotFound>> (
Guid id, IOrderQueries queries, CancellationToken ct) =>
await queries.GetAsync(id, ct) is { } dto ? TypedResults.Ok(dto) : TypedResults.NotFound());
app.Run();
public record OrderDto(Guid Id, string Status);
public interface IOrderQueries { Task<OrderDto?> GetAsync(Guid id, CancellationToken ct); }
AddJwtBearer needs the Microsoft.AspNetCore.Authentication.JwtBearer package; register an IOrderQueries implementation before running.
.NET 10 generates a public Program class, so WebApplicationFactory<Program> works unchanged (analyzer ASP0027 flags a manual declaration). On .NET 8/9 add public partial class Program { } at the end of Program.cs.
AddValidation() uses a source generator that only sees types in the assembly that calls it; call it in the assembly that defines the endpoints. Opt out per endpoint with .DisableValidation().
3. Dependency injection lifetimes
Lifetime
Use for
Pitfall
Singleton
Stateless, thread-safe services, caches
Captive dependency: holding a scoped DbContext shares it across requests
Scoped
DbContext, unit of work, per-request context
Resolving from the root provider throws under ValidateScopes
Transient
Light stateless helpers
Disposable transients resolved from the root live until shutdown
ValidateScopes and ValidateOnBuild are on in Development, which is where "Cannot consume scoped service 'X' from singleton 'Y'" comes from. The fix is a scope per unit of work, never making the DbContext a singleton:
// inside the singleton or BackgroundService; scopeFactory is an injected IServiceScopeFactory
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OrdersDbContext>();
Wrap each BackgroundService iteration in try/catch and honour stoppingToken: an unhandled exception stops the host. Full worker: references/background-and-streaming.md. Constructor injection only (primary constructors are fine); no IServiceProvider.GetService in business code. Keyed services replace hand-rolled factories for named variants.
4. Configuration, options and secrets
Typed options validated at startup: services.AddOptions<PaymentOptions>().BindConfiguration("Payment").ValidateDataAnnotations().ValidateOnStart();
appsettings.{Environment}.json holds non-secret differences only. Secrets come from User Secrets locally and the platform secret store in deployed environments; prefer workload identity over passwords in connection strings.
5. Async and language rules
Async all the way: never .Result, .Wait() or .GetAwaiter().GetResult() on a request path; they block pool threads and starve the service under load.
Accept a CancellationToken in every endpoint and pass it to every EF, HttpClient and stream call.
No async void; no fire-and-forget Task from a request (it outlives the scope → ObjectDisposedException). Hand work to a channel or queue.
<Nullable>enable</Nullable> with nullable warnings as errors; fix the flow instead of !. record for DTOs, required/init for mandatory members, sealed by default, TimeProvider instead of DateTime.UtcNow.
6. Validation and errors
Validate at the edge (§1); invariants that must always hold live in the domain type's constructor or factory as well.
AddProblemDetails() + UseExceptionHandler() + UseStatusCodePages() give ProblemDetails for every failure; map known exceptions with IExceptionHandler (sample in references/program-baseline.md).
Never return stack traces or exception messages outside Development; log with the trace id and return that id in the problem.
7. EF Core correctness
Scoped AddDbContext; IDbContextFactory<T> for background or parallel work. A context is not thread-safe: no Task.WhenAll over one context.
Reads: AsNoTracking() plus Select into a DTO; no lazy loading in APIs. Query tuning (split queries, keyset paging, compiled queries) belongs to dotnet-performance.
Raw SQL: FromSql($"…{id}") and SqlQuery<T> parameterise interpolation; FromSqlRaw never with concatenation.
Concurrency: a row-version token on aggregates edited concurrently; catch DbUpdateConcurrencyException and return 409 or 412.
Migrations: one per change, applied by a pipeline step (migration bundle or idempotent script), never Database.Migrate() at start-up of a multi-instance service. Zero-downtime rules: database-migrations.
8. Outbound HTTP, logging, auth, OpenAPI
AddHttpClient<PaymentsClient>(…).AddStandardResilienceHandler() (package Microsoft.Extensions.Http.Resilience): total timeout 30 s, retry, circuit breaker, attempt timeout. It retries all methods by default; call options.Retry.DisableForUnsafeHttpMethods() unless the call carries an idempotency key. Never new HttpClient() per call.
ILogger<T> with message templates ("Order {OrderId} placed"), never interpolation; [LoggerMessage] source generator on hot paths; no secrets, tokens or bodies in logs.
Policies, not role strings: AddAuthorizationBuilder().AddPolicy("orders:write", p => p.RequireClaim("scope", "orders.write")). A fallback policy requires authentication; AllowAnonymous is explicit. Resource ownership is checked in the handler or with IAuthorizationService.
AddOpenApi() + MapOpenApi() emit OpenAPI 3.1 by default on .NET 10; MapOpenApi("/openapi/{documentName}.yaml") emits YAML. Generate the document at build time and diff it in CI. Contract rules: api-design.
9. Deliverable format
## Files changed full code for new files, focused diffs for edits, Program.cs registrations included
## Why one line per non-obvious decision (lifetime, tracking mode, resilience, validation)
## Config & secrets new options keys, secrets the operator must supply, migration name
## Tests what to add and where (hand over to dotnet-testing), how to run
## Risks behaviour changes, rollout order, version features used (.NET 10 only?)
Checklist
Target framework checked; no API newer than the project's version.
Endpoint is thin, returns TypedResults, takes a CancellationToken, requires authorization or says why not.
Input validated by the solution's single validation mechanism; errors are ProblemDetails.
No scoped service captured by a singleton; background work creates a scope per iteration.
No .Result/.Wait()/async void; every I/O call receives the token.
Reads use AsNoTracking + projection; SQL is parameterised.
Outbound calls use a typed client with timeouts; retries only where idempotent.
No secret in appsettings*.json, code or logs; options validated on start.
Log calls use message templates.
OpenAPI output still describes every response the endpoint can return.
Anti-patterns
Singleton holding a DbContext → inject IServiceScopeFactory and create a scope per unit of work (§3).
.Result to "make it sync" → make the caller async; at the top level use await in Main.
Retrying a POST with the standard handler defaults → DisableForUnsafeHttpMethods() or an idempotency key.
Database.Migrate() in Program.cs → migration bundle in the pipeline (database-migrations).
catch (Exception) { return null; } → let it reach the exception handler, or map it to a typed result.
$"Order {id}" in log calls → message template with named placeholders.
! to silence nullable warnings → model the absence (T?, Results<…, NotFound>).
Business rules in endpoint lambdas → handler or service class that tests can call without HTTP.
Go deeper
references/program-baseline.md — complete Program.cs for an API (ProblemDetails, IExceptionHandler, validation, JWT, policies, rate limiter, OpenAPI, typed client with resilience) and Directory.Build.props.
references/background-and-streaming.md — Channel<T> work queue, IAsyncEnumerable and TypedResults.ServerSentEvents streaming, HybridCache usage, Native AOT constraints.
Sibling skills: dotnet-testing for tests, dotnet-performance for symptoms, dotnet-architecture for solution structure, api-design for contracts, database-migrations, service-operability (health, shutdown, telemetry), backend-code-review for reviews.
---
name: dotnet-development
description: >
Write production-grade C# and ASP.NET Core services on .NET 10 (with .NET 8 notes) — minimal APIs vs controllers, DI lifetimes, options and secrets, async/await with cancellation, nullable reference types, validation with AddValidation, ProblemDetails errors, EF Core usage, IHttpClientFactory with the standard resilience handler, structured logging, JWT and policy authorization, background services and built-in OpenAPI. Use this whenever the user asks to write, refactor, debug or explain C# back-end code; edits Program.cs, appsettings.json, a DbContext, entity configurations, controllers, endpoint mappings, middleware, hosted services or HttpClient registrations; hits a deadlock, ObjectDisposedException, "Cannot consume scoped service from singleton", nullable warnings; or asks "how do I do X in ASP.NET Core". Also use it when a Node or Java developer asks for the ASP.NET Core equivalent of a pattern. For tests use dotnet-testing; for slow or memory-hungry services use dotnet-performance.
metadata:
technology: .NET
type: development
---
# .NET Development
> **Targets:** .NET 10 LTS, ASP.NET Core 10, EF Core 10, C# 14 (.NET 8 LTS noted where different) · **Verified:** 2026-09 against https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-10.0
Write every service as if it runs under load, behind a load balancer, with requests cancelled mid-flight and configuration injected by the platform. **Check the version first:** read `global.json`, `<TargetFramework>` and `Directory.Packages.props`. Do not use keyed services or `IExceptionHandler` below .NET 8, `AddOpenApi` below .NET 9, or `AddValidation` and `TypedResults.ServerSentEvents` below .NET 10.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| Endpoint style | **Minimal APIs**: `MapGroup` per feature, `TypedResults` | A large controller codebase already exists → stay with `[ApiController]`; Native AOT → minimal APIs only |
| Validation | `AddValidation()` with DataAnnotations (.NET 10+) | Cross-field or async rules → FluentValidation; controllers → `[ApiController]` model validation. One mechanism per solution |
| Error shape | RFC 9457 ProblemDetails from `AddProblemDetails()` | Never a custom envelope |
| Data access | EF Core 10, scoped `DbContext`, projection to DTOs | Bulk or reporting SQL → `SqlQuery<T>` or Dapper next to EF |
| Outbound HTTP | Typed client + `AddStandardResilienceHandler()` | Non-idempotent calls → disable retries or send an idempotency key |
| Background work | `BackgroundService` + scope per iteration | Must survive restarts → broker or job library, see `messaging-patterns` |
| Caching shared data | `HybridCache` | Per-instance, tiny and static → `IMemoryCache` |
## 2. Thin endpoints
Bind, validate, call one handler, map the result. No EF queries or business rules inside `Program.cs` lambdas.
```csharp
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddValidation(); // .NET 10+
builder.Services.AddAuthentication().AddJwtBearer(); // reads Authentication:Schemes:Bearer
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseExceptionHandler(); // parameterless overload needs AddProblemDetails()
app.UseStatusCodePages();
var orders = app.MapGroup("/orders").WithTags("Orders").RequireAuthorization();
orders.MapGet("/{id:guid}", async Task<Results<Ok<OrderDto>, NotFound>> (
Guid id, IOrderQueries queries, CancellationToken ct) =>
await queries.GetAsync(id, ct) is { } dto ? TypedResults.Ok(dto) : TypedResults.NotFound());
app.Run();
public record OrderDto(Guid Id, string Status);
public interface IOrderQueries { Task<OrderDto?> GetAsync(Guid id, CancellationToken ct); }
```
- `AddJwtBearer` needs the `Microsoft.AspNetCore.Authentication.JwtBearer` package; register an `IOrderQueries` implementation before running.
- .NET 10 generates a public `Program` class, so `WebApplicationFactory<Program>` works unchanged (analyzer ASP0027 flags a manual declaration). On .NET 8/9 add `public partial class Program { }` at the end of `Program.cs`.
- `AddValidation()` uses a source generator that only sees types in the assembly that calls it; call it in the assembly that defines the endpoints. Opt out per endpoint with `.DisableValidation()`.
## 3. Dependency injection lifetimes
| Lifetime | Use for | Pitfall |
|---|---|---|
| Singleton | Stateless, thread-safe services, caches | **Captive dependency**: holding a scoped `DbContext` shares it across requests |
| Scoped | `DbContext`, unit of work, per-request context | Resolving from the root provider throws under `ValidateScopes` |
| Transient | Light stateless helpers | Disposable transients resolved from the root live until shutdown |
`ValidateScopes` and `ValidateOnBuild` are on in Development, which is where "Cannot consume scoped service 'X' from singleton 'Y'" comes from. The fix is a scope per unit of work, never making the `DbContext` a singleton:
```csharp
// inside the singleton or BackgroundService; scopeFactory is an injected IServiceScopeFactory
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OrdersDbContext>();
```
Wrap each `BackgroundService` iteration in try/catch and honour `stoppingToken`: an unhandled exception stops the host. Full worker: `references/background-and-streaming.md`. Constructor injection only (primary constructors are fine); no `IServiceProvider.GetService` in business code. Keyed services replace hand-rolled factories for named variants.
## 4. Configuration, options and secrets
- Typed options validated at startup: `services.AddOptions<PaymentOptions>().BindConfiguration("Payment").ValidateDataAnnotations().ValidateOnStart();`
- `appsettings.{Environment}.json` holds non-secret differences only. Secrets come from User Secrets locally and the platform secret store in deployed environments; prefer workload identity over passwords in connection strings.
## 5. Async and language rules
- Async all the way: never `.Result`, `.Wait()` or `.GetAwaiter().GetResult()` on a request path; they block pool threads and starve the service under load.
- Accept a `CancellationToken` in every endpoint and pass it to every EF, `HttpClient` and stream call.
- No `async void`; no fire-and-forget `Task` from a request (it outlives the scope → `ObjectDisposedException`). Hand work to a channel or queue.
- `<Nullable>enable</Nullable>` with nullable warnings as errors; fix the flow instead of `!`. `record` for DTOs, `required`/`init` for mandatory members, `sealed` by default, `TimeProvider` instead of `DateTime.UtcNow`.
## 6. Validation and errors
- Validate at the edge (§1); invariants that must always hold live in the domain type's constructor or factory as well.
- `AddProblemDetails()` + `UseExceptionHandler()` + `UseStatusCodePages()` give ProblemDetails for every failure; map known exceptions with `IExceptionHandler` (sample in `references/program-baseline.md`).
- Never return stack traces or exception messages outside Development; log with the trace id and return that id in the problem.
## 7. EF Core correctness
- Scoped `AddDbContext`; `IDbContextFactory<T>` for background or parallel work. A context is not thread-safe: no `Task.WhenAll` over one context.
- Reads: `AsNoTracking()` plus `Select` into a DTO; no lazy loading in APIs. Query tuning (split queries, keyset paging, compiled queries) belongs to `dotnet-performance`.
- Raw SQL: `FromSql($"…{id}")` and `SqlQuery<T>` parameterise interpolation; `FromSqlRaw` never with concatenation.
- Concurrency: a row-version token on aggregates edited concurrently; catch `DbUpdateConcurrencyException` and return 409 or 412.
- Migrations: one per change, applied by a pipeline step (migration bundle or idempotent script), never `Database.Migrate()` at start-up of a multi-instance service. Zero-downtime rules: `database-migrations`.
## 8. Outbound HTTP, logging, auth, OpenAPI
- `AddHttpClient<PaymentsClient>(…).AddStandardResilienceHandler()` (package `Microsoft.Extensions.Http.Resilience`): total timeout 30 s, retry, circuit breaker, attempt timeout. It retries **all** methods by default; call `options.Retry.DisableForUnsafeHttpMethods()` unless the call carries an idempotency key. Never `new HttpClient()` per call.
- `ILogger<T>` with message templates (`"Order {OrderId} placed"`), never interpolation; `[LoggerMessage]` source generator on hot paths; no secrets, tokens or bodies in logs.
- Policies, not role strings: `AddAuthorizationBuilder().AddPolicy("orders:write", p => p.RequireClaim("scope", "orders.write"))`. A fallback policy requires authentication; `AllowAnonymous` is explicit. Resource ownership is checked in the handler or with `IAuthorizationService`.
- `AddOpenApi()` + `MapOpenApi()` emit OpenAPI **3.1** by default on .NET 10; `MapOpenApi("/openapi/{documentName}.yaml")` emits YAML. Generate the document at build time and diff it in CI. Contract rules: `api-design`.
## 9. Deliverable format
```
## Files changed full code for new files, focused diffs for edits, Program.cs registrations included
## Why one line per non-obvious decision (lifetime, tracking mode, resilience, validation)
## Config & secrets new options keys, secrets the operator must supply, migration name
## Tests what to add and where (hand over to dotnet-testing), how to run
## Risks behaviour changes, rollout order, version features used (.NET 10 only?)
```
## Checklist
- [ ] Target framework checked; no API newer than the project's version.
- [ ] Endpoint is thin, returns `TypedResults`, takes a `CancellationToken`, requires authorization or says why not.
- [ ] Input validated by the solution's single validation mechanism; errors are ProblemDetails.
- [ ] No scoped service captured by a singleton; background work creates a scope per iteration.
- [ ] No `.Result`/`.Wait()`/`async void`; every I/O call receives the token.
- [ ] Reads use `AsNoTracking` + projection; SQL is parameterised.
- [ ] Outbound calls use a typed client with timeouts; retries only where idempotent.
- [ ] No secret in `appsettings*.json`, code or logs; options validated on start.
- [ ] Log calls use message templates.
- [ ] OpenAPI output still describes every response the endpoint can return.
## Anti-patterns
- **Singleton holding a `DbContext`** → inject `IServiceScopeFactory` and create a scope per unit of work (§3).
- **`.Result` to "make it sync"** → make the caller async; at the top level use `await` in `Main`.
- **Retrying a POST with the standard handler defaults** → `DisableForUnsafeHttpMethods()` or an idempotency key.
- **`Database.Migrate()` in `Program.cs`** → migration bundle in the pipeline (`database-migrations`).
- **`catch (Exception) { return null; }`** → let it reach the exception handler, or map it to a typed result.
- **`$"Order {id}"` in log calls** → message template with named placeholders.
- **`!` to silence nullable warnings** → model the absence (`T?`, `Results<…, NotFound>`).
- **Business rules in endpoint lambdas** → handler or service class that tests can call without HTTP.
## Go deeper
- `references/program-baseline.md` — complete `Program.cs` for an API (ProblemDetails, `IExceptionHandler`, validation, JWT, policies, rate limiter, OpenAPI, typed client with resilience) and `Directory.Build.props`.
- `references/background-and-streaming.md` — `Channel<T>` work queue, `IAsyncEnumerable` and `TypedResults.ServerSentEvents` streaming, `HybridCache` usage, Native AOT constraints.
- Sibling skills: `dotnet-testing` for tests, `dotnet-performance` for symptoms, `dotnet-architecture` for solution structure, `api-design` for contracts, `database-migrations`, `service-operability` (health, shutdown, telemetry), `backend-code-review` for reviews.