К основному содержанию
скилл CX Codex

scaffold — скилл для Claude Code: каркас фич в .NET 10

Создаёт полный набор файлов для новой фичи в .NET 10: endpoint, handler, валидатор, DTO, конфигурацию EF и интеграционные тесты.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add codewithmukesh/dotnet-claude-kit --skill scaffold -a claude-code
Открыть на GitHub

Что делает scaffold

Скилл сначала определяет архитектуру проекта — Vertical Slice, Clean Architecture, DDD или Modular Monolith. Дальше он смотрит на существующие соглашения: имена классов, структуру папок, подход к валидации, организацию тестов. И только потом генерирует файлы по шаблонам выбранной архитектуры.

Внутри жёсткий чек-лист из девяти пунктов, который обязана пройти каждая фича. Endpoint через IEndpointGroup, handler с sealed и primary constructor, правила FluentValidation, DTO-записи, IEntityTypeConfiguration<T>, интеграционные тесты на WebApplicationFactory и Testcontainers, метаданные OpenAPI, CancellationToken в каждом асинхронном вызове и паттерн Result<T>. Пропустить пункт нельзя — скилл не отдаёт половину фичи.

После генерации он сам собирает проект и прогоняет тесты через dotnet build --no-restore и dotnet test --no-build --filter "FullyQualifiedName~{FeatureName}". Если сборка падает, скилл правит и запускает заново. Для работы нужен .NET 10 SDK, а интеграционные тесты опираются на Testcontainers — значит, на машине должен быть доступен Docker.

Какие задачи решает

  • создать endpoint с handler и валидатором в один заход
  • разложить файлы новой фичи по слоям Clean Architecture
  • сгенерировать CRUD для сущности вместе с EF-конфигурацией
  • добавить интеграционный тест к каждой новой фиче
  • подстроить генерацию под уже принятые в проекте соглашения

Примеры запросов агенту

  • /scaffold фича Product Catalog с CRUD
  • создай endpoint для заказов в стиле Vertical Slice
  • добавь сущность Invoice с полями и инвариантами

Как установить scaffold

1Через Skills CLI (Vercel)

npx skills add codewithmukesh/dotnet-claude-kit --skill scaffold -a claude-code

2Вручную: положить файлы

~/.claude/skills/scaffold/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/scaffold/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора46

outdated Собирает отчёт о здоровье зависимостей .NET: устаревшие NuGet-пакеты, уязвимые версии и ловушки с коммерческими лицензиями. CX Codex +1 2 800установок arch-check Сверяет кодовую базу с заявленной архитектурой: направление зависимостей, нарушения слоёв, утечки между модулями и циклы. Пригодится перед релизом или после крупной фичи. CX Codex +1 2 800установок migrate Скилл ведёт разработчика через миграции схемы EF Core, смену версии .NET и обновление NuGet. На каждом шаге он готовит план отката и запускает тесты. CX Codex +1 2 800установок plan Составляет план реализации для .NET-задач с учётом архитектуры проекта. Нужен перед изменениями, которые затрагивают несколько слоёв или модулей. CX Codex +1 2 800установок build-fix Запускает автономный цикл починки сборки и тестов в проектах на .NET. Скилл разбирает ошибки компилятора, исправляет код и останавливается при регрессиях. CX Codex +1 2 800установок spec Превращает сырую идею фичи в письменную спецификацию с критериями приёмки. Задаёт вопросы раундами, пока не закроет все пробелы. CX Codex +1 2 800установок checkpoint Делает git-коммит с описанием и короткую заметку о состоянии работы, не завершая сессию. Пригодится перед рискованным рефактором. CX Codex +1 2 800установок tdd Скилл ведёт строгий цикл разработки через тестирование в .NET 10: от падающего теста в xUnit v3 до минимального кода и рефакторинга. CX Codex +1 2 800установок

Похожие

dotnet-backend-patterns Seth Hobson Скилл для разработки на C# и .NET: паттерны асинхронного кода, внедрение зависимостей, Entity Framework Core, кэширование и тестирование. Нужен, если вы пишете backend API, MCP-серверы или рецензируете код на C#. CX Codex 19 076установок optimizing-ef-core-queries dotnet Разбирает доступ к данным на EF Core в сервисах, репозиториях и фоновых заданиях и показывает, где запросы тормозят, дублируют строки или бьют по базе лишний раз. CX Codex +1 5 700установок dotnet-patterns affaan-m Набор архитектурных правил C# и ASP.NET Core для ИИ-ассистентов. Задаёт стандарты написания чистого кода, работы с DI, асинхронностью и обработкой ошибок. CX Codex +1 4 600установок migrate-dotnet10-to-dotnet11 dotnet Скилл переводит проекты и решения с .NET 10 на .NET 11. Он обновляет целевой фреймворк, пакеты и исправляет несовместимости C# 15 и EF Core 11. CX Codex +1 3 400установок csharp официальный github Правило задаёт Copilot стиль C#-кода: именование, nullable-типы, форматирование и работу с ASP.NET Core. Пригодится, если агент пишет по-разному в каждом файле. ★ 40 418звёзд репо creating-oracle-to-postgres-migration-integration-tests официальный github Создаёт интеграционные тесты для .NET-артефактов доступа к данным, проверяя поведение Oracle перед миграцией проекта на PostgreSQL. 1 800установок

Рядом в теме «Бэкенд и API»

Всё по теме «Бэкенд и API» →

Вопросы о scaffold

Как установить scaffold в Claude?

Выполните npx skills add codewithmukesh/dotnet-claude-kit --skill scaffold -a claude-code. Скилл появится в ~/.claude/skills/scaffold/SKILL.md.

Что делает scaffold?

Определяет архитектуру проекта и генерирует полную фичу: endpoint, handler, валидатор, DTO, конфигурацию EF и интеграционные тесты. Затем собирает проект и прогоняет тесты.

Какие архитектуры поддерживает scaffold?

Vertical Slice, Clean Architecture, DDD с Clean Architecture и Modular Monolith. Карты размещения файлов и шаблоны кода лежат в references/architecture-patterns.md.

Исходный текст

SKILL.md · MIT
---
name: scaffold
description: >
  Architecture-aware feature scaffolding for .NET 10 projects. Detects the
  project's architecture (VSA, Clean Architecture, DDD, Modular Monolith) and
  generates complete feature slices with all required layers: endpoint,
  handler, validator, DTOs, EF configuration, and integration tests — with
  the completeness checklist and per-architecture code templates every
  generated feature must satisfy.
  Use when: "scaffold", "create feature", "add feature", "new endpoint",
  "generate", "add entity", "scaffold a module", "add module", or when
  customizing generation templates or defining what a complete feature slice
  includes.
---

# /scaffold — Architecture-Aware Feature Scaffolding

## What

Generates a complete feature with all required files based on the project's
architecture. Never generates half a feature — every scaffold includes the
endpoint, handler, validation, DTOs, EF configuration, and at least one
integration test as a single unit, written in modern C# 14 (primary
constructors, collection expressions, records, sealed handlers, TypedResults).

Supported architectures (file placement maps and code shape templates live in
`references/architecture-patterns.md`):

- **Vertical Slice Architecture (VSA)** — single-file features in `Features/`
- **Clean Architecture (CA)** — files split across Domain, Application, Infrastructure, Api
- **DDD + Clean Architecture** — aggregate roots, value objects, domain events, plus CA layers
- **Modular Monolith** — self-contained modules with their own DbContext and integration events

## When

- "Scaffold a [feature name]", "create an endpoint for", "add a feature"
- "Generate CRUD for", "add entity", "new module", "scaffold a module"
- Starting a new feature after `/plan` has produced an approved plan
- Customizing generation templates or defining what a complete slice includes
- Any time the user wants a complete, working feature skeleton

## How

### Step 1: Detect Architecture

Use the `architecture-advisor` skill to determine the project's architecture:
- Examine folder structure, project references, and existing patterns
- If architecture is ambiguous, ask the user rather than guessing
- Load the matching architecture skill (vertical-slice, clean-architecture, ddd)

### Step 2: Clarify Scope

Confirm with the user before generating (skip anything the plan already answers):
1. Feature/entity name and operations needed — full CRUD or a subset?
2. Key fields and invariants for any new entity
3. Module placement (Modular Monolith only) — existing module or new one?

### Step 3: Learn Conventions

Use the `convention-learner` skill and MCP tools to check:
- Naming patterns (`*Handler`, `*Service`, `*Endpoint`, `*Command`, `*Query`)
- Folder structure, file organization, access modifiers, sealed conventions
- Existing validation approach (FluentValidation, data annotations, manual)
- Test project structure and naming (`*Tests`, `*IntegrationTests`)

Match what exists. Do not impose new conventions on an established codebase.

### Step 4: Generate All Layers

Generate every file the architecture requires, following the templates in
`references/architecture-patterns.md`:

- **VSA** — read the VSA section: single-file feature + endpoint group + EF config + tests
- **Clean Architecture** — read the CA section: Mediator command/handler in Application, endpoint in Api
- **DDD** — read the DDD section: aggregate with invariants and domain events, thin handler
- **Modular Monolith** — read the Modular Monolith section: module DbContext, DI registration, integration events

The reference also covers the shared shapes every architecture reuses
(endpoint group, validator, entity + `IEntityTypeConfiguration<T>` pair,
test fixture) and the anti-patterns to avoid.

### Step 5: Completeness Checklist (MANDATORY)

Every scaffolded feature MUST include ALL nine items. Do not skip any:

- [ ] **Endpoint** — `IEndpointGroup` file with a route group; never wired in Program.cs
- [ ] **Handler** — `sealed`, primary constructor, one per operation
- [ ] **Validator** — FluentValidation rules with meaning (ranges, required, max lengths), wired via `.AddEndpointFilter<ValidationFilter<T>>()` on mutating endpoints
- [ ] **DTOs** — records shaped for the consumer, never 1:1 entity mirrors
- [ ] **EF configuration** — `IEntityTypeConfiguration<T>`; no data annotations on entities
- [ ] **Integration tests** — `WebApplicationFactory` + Testcontainers, DI replacement via `services.RemoveAll<DbContextOptions<T>>()`
- [ ] **OpenAPI metadata** — `.WithName()`, `.WithSummary()`, `.Produces<T>()`, `.ProducesValidationProblem()`, `.ProducesProblem(404)`
- [ ] **CancellationToken** — on every async method and passed to every async call
- [ ] **Result pattern** — handlers return `Result<T>`; endpoints map success → TypedResults, failure → `ToProblemDetails()`

Also verify supporting infrastructure — scaffold it if missing: list endpoints
get bounded pagination (`page`/`pageSize`, max 50), Program.cs has
`app.UseExceptionHandler()`, and appsettings.json has a connection string.

### Step 6: Verify

Prove the scaffold works before reporting done:

```bash
dotnet build --no-restore
dotnet test --no-build --filter "FullyQualifiedName~{FeatureName}"
```

If the build or tests fail, fix and re-run before presenting results.

## Example

```
User: /scaffold a Product Catalog feature with CRUD operations

Claude: Detected architecture: Vertical Slice Architecture

Created files:
  src/Features/Products/CreateProduct.cs     -- Command + handler + validator
  src/Features/Products/GetProduct.cs        -- Query by ID + handler
  src/Features/Products/ListProducts.cs      -- Paginated list + handler
  src/Features/Products/UpdateProduct.cs     -- Command + handler + validator
  src/Features/Products/DeleteProduct.cs     -- Command + handler
  src/Features/Products/ProductEndpoints.cs  -- IEndpointGroup, OpenAPI metadata
  src/Features/Products/ProductConfig.cs     -- EF Core configuration
  tests/Features/Products/CreateProductTests.cs
  tests/Features/Products/GetProductTests.cs
  tests/Features/Products/ListProductsTests.cs

Checklist: 9/9 | Build: PASS | Tests: PASS

All files follow your existing conventions (sealed handlers,
primary constructors, TypedResults return types).
```

## Related

- `dotnet-init` — Initialize the project and CLAUDE.md before scaffolding features
- `vertical-slice` — The VSA patterns the VSA scaffold follows
- `clean-architecture` — Layering rules behind the CA scaffold
- `ddd` — Aggregate and domain-event patterns behind the DDD scaffold
- `project-structure` — Where files belong in each architecture

© codewithmukesh · MIT · codewithmukesh/dotnet-claude-kit

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой