# Pathrule Pattern: ASP.NET Core (1.0.0)
# ::pathrule:package:aspnet-core

### [RULE] Middleware order is an explicit security and behavior contract  (path: /src/Web)
<!-- scope: folder | priority: high | strict -->

ASP.NET Core middleware runs in registration order on the request path and unwinds in reverse on the response path, so ordering changes behavior. Keep the production pipeline readable in one composition root or clearly ordered extensions, and document why middleware that depends on routing, identity, endpoint metadata, or response handling sits where it does. Do not rely on template defaults after adding custom requirements.

- Place authentication before authorization and position CORS, forwarded headers, exception handling, rate limiting, static files, and endpoint-aware middleware according to their data dependencies.
- Avoid terminal middleware before endpoints unless it intentionally owns the remaining path.
- Keep development-only diagnostics out of production and produce safe errors through the approved handler.
- Add integration tests for protected endpoints, preflight requests, forwarded scheme, errors, static files, and unknown routes.

Verification: Trace representative requests through the actual configured pipeline and confirm each middleware sees the context and endpoint metadata it requires.

---

### [RULE] Options bind to typed contracts and validate at startup  (path: /src/Infrastructure)
<!-- scope: folder | priority: high | strict -->

Scattered IConfiguration string lookups hide missing values, parse failures, security assumptions, and override behavior until a deep request executes. Bind each owned configuration section to a typed options class, validate required fields, ranges, formats, cross-field invariants, and referenced resources, and fail startup with actionable non-secret messages for configuration that must be valid for the deployment.

- Keep secret values in approved external inputs and prevent option logging, validation errors, or diagnostics from printing them.
- Use named options only when variants have clear owners and consumers; avoid a global settings bag.
- Decide which options may reload safely and which require immutable startup state or coordinated restart.
- Test representative production sources and precedence, including absent, malformed, conflicting, and environment-specific values.

Verification: Boot the application with each required value missing or invalid and confirm failure happens before the listener or background consumer becomes ready.

---

### [RULE] Dependency lifetimes match ownership and concurrency  (path: /src/Infrastructure)
<!-- scope: folder | priority: high | strict -->

The container cannot make a stateful service thread-safe or extend a disposed scope correctly. Use singleton only for thread-safe state that truly spans the application, scoped for one request or explicit operation scope, and transient for lightweight independent instances. Never capture a scoped dependency in a singleton, hosted service, or conventional middleware constructor.

- Resolve scoped services inside an explicit scope for background work and dispose the scope after the operation.
- Inject scoped dependencies into middleware Invoke or InvokeAsync, or use factory-based middleware when constructor injection needs request scope.
- Treat DbContext as an operation-scoped unit of work and avoid concurrent use across tasks.
- Enable scope and build validation in development and tests, then add concurrency and disposal tests for custom factories.

Verification: Start the real container, execute concurrent requests and background iterations, and confirm no captive dependency, cross-request state, concurrent context use, or disposal leak appears.

---

### [MEMORY] Minimal APIs and controllers are HTTP adapters  (path: /src/Web)

Minimal APIs provide a concise route-handler model and controllers provide established conventions and extensibility. Neither choice justifies placing persistence queries, transactions, provider calls, or domain branching directly in an HTTP adapter. Bind and validate request contracts, derive identity and tenant from server context, authorize the action, call one application operation, and map typed outcomes to stable responses.

Use route groups, endpoint filters, conventions, or controller filters only for concerns whose ordering and scope remain obvious. Keep persistence entities out of public serialization and generate OpenAPI from the same contracts tested by clients. See /src/Application for the use-case boundary and /tests for focused adapter tests.

---

### [MEMORY] Cancellation and async flow reach every owned dependency  (path: /src/Application)

ASP.NET Core exposes request cancellation, but it only saves resources when every owned asynchronous boundary accepts and observes the CancellationToken. Pass it through application operations, EF Core queries and saves, HTTP client calls, stream copies, locks, delays, and queue or workflow submission where cancellation is safe. Avoid Task.Run around ordinary async I/O and never use async void for request work.

Define the commit point after which client disconnect cannot cancel a durable required effect, and use an outbox or background workflow for work that must survive the request. Distinguish cancellation from timeout and unexpected failure in telemetry without returning internal detail. Test cancellation before and after the commit point. See /src/Infrastructure for lifetime and resource cleanup.

---

### [MEMORY] Problem Details is the public error contract  (path: /src/Web)

Clients need a predictable error shape, not exception class names or environment-dependent text. Use Problem Details or an equivalent consistent contract with stable type or code, HTTP status, safe title, optional field-level validation errors, and a correlation reference. Map domain conflicts, missing resources, authorization denials, rate limits, and dependency failures through one reviewed policy.

Do not expose stack traces, SQL, connection details, provider payloads, secrets, or existence information that authorization intends to hide. Log unexpected exceptions once at the authoritative boundary with trace correlation and return a generic public result. Keep status and retry semantics consistent across Minimal APIs and controllers. See /tests for contract coverage.

---

### [MEMORY] EF Core migrations are reviewed deployment artifacts  (path: /src/Infrastructure)

A generated EF Core migration is a starting artifact, not proof that a production database change is safe. Review operations, provider-specific SQL, defaults, indexes, constraints, data size, lock behavior, transaction limits, and reversibility. Separate large backfills from schema deployment and keep old and new application versions compatible during the rollout window.

Generate migrations from the intended model and verify no unrelated drift appears. Apply them through one controlled deployment identity rather than every web instance racing at startup. Test on production-like data volume, record migration history evidence, and use roll-forward recovery when rollback would lose accepted data. See /src/Application for behavior compatibility and /tests for integration coverage.

---

### [SKILL] review-aspnet-core-service  (path: /tests)

---
name: review-aspnet-core-service
description: Review an ASP.NET Core service for runtime ordering, lifetime safety, validated contracts, and deployment behavior.
---

# Review ASP.NET Core Service

1. Trace application startup, configuration sources, typed options validation, service registrations, hosted services, middleware order, endpoint mapping, readiness, and shutdown.
2. Follow representative public and protected requests through binding, validation, identity, tenant, authorization, application operation, DbContext transaction, external effects, cancellation, and Problem Details.
3. Inspect singleton, scoped, transient, middleware, HttpClient, DbContext, stream, and background-work ownership for concurrency, captive dependencies, disposal, and retry behavior.
4. Review EF Core model changes and migrations for drift, locks, backfill, compatibility, deployment ordering, failure recovery, and production-like evidence.
5. Run focused unit and adapter tests plus real-container integration cases for pipeline ordering, configuration failure, authorization, errors, cancellation, concurrency, and database behavior.

Record failed boundaries and rerun the smallest test that proves each correction before completing the review.
