migrate-static-to-wrapper
Qué hace
Esta skill mueve código de C# desde llamadas estáticas directas, como leer la hora actual o un archivo, a envoltorios inyectados o abstracciones integradas. Es para desarrolladores que quieren hacer el código comprobable en pasos pequeños y controlados.
Cuándo usarla
- ✓Cuando quieres reemplazar DateTime.UtcNow o DateTime.Now por TimeProvider en un proyecto.
- ✓Cuando las llamadas directas a File deben pasar a un envoltorio de sistema de archivos existente en un namespace.
- ✓Cuando una clase necesita inyección por constructor para una nueva abstracción y sus pruebas necesitan versiones falsas.
Link de la skill
https://github.com/dotnet/skills/blob/main/plugins/dotnet-test/skills/migrate-static-to-wrapper/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Reemplaza las llamadas directas a DateTime.UtcNow de mi proyecto Orders por TimeProvider, y actualiza las pruebas para usar un reloj falso.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
El agente limita el trabajo al alcance que indiques, cambia las llamadas y los constructores para usar la abstracción inyectada, y actualiza las pruebas afectadas con versiones falsas.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
Migrate Static to Wrapper
Perform mechanical, codemod-style replacement of static dependency call sites with calls to injected wrapper interfaces or built-in abstractions. Operates on a bounded scope (single file, project, or namespace) so migrations can be done incrementally.
When to Use
- After wrappers have been generated (via
generate-testability-wrappers) or built-in abstractions identified - Migrating
DateTime.UtcNow→TimeProvider.GetUtcNow()across a project - Migrating
File.*→IFileSystem.File.*across a namespace - Adding constructor injection for the new abstraction to affected classes
- Making a
staticutility class testable by adding an ambient seam (Step 3) while its existing call sites keep compiling unchanged - Incremental migration: one project or namespace at a time
- Updating affected tests with fakes when the requested migration names the replacement abstraction
When Not to Use
- No wrapper or abstraction exists yet and one must be designed from scratch (use
generate-testability-wrappersfirst). A built-in abstraction such asTimeProviderorIFileSystemalways counts as existing. - The user wants to detect statics, not migrate them (use
detect-static-dependencies) - Migrating between test frameworks (use the appropriate migration skill)
- The user primarily asks for a deterministic behavior test and has not selected
the production seam (use
testability-obstacle)
A class that is
static, or a project with no DI container, is not a reason to skip this skill — that is exactly what the ambient seam in Step 3 is for. Use it whenever the call sites must keep compiling unchanged.
Inputs
| Input | Required | Description |
|---|---|---|
| Static pattern | No | Infer from the request and discovered call sites (e.g., DateTime.UtcNow, File.ReadAllText) |
| Replacement abstraction | No | Infer from the request and existing project abstractions; stop only when no named/existing abstraction is available |
| Scope | No | Infer from the requested file/project/namespace, otherwise discover the narrowest relevant workspace scope |
| Injection strategy | No | constructor (default), primary-constructor, or ambient |
Workflow
Non-negotiable migration boundaries
- Missing abstraction means stop. If the named interface/package is absent and the request only authorizes call-site replacement, do not add a package, invent a local lookalike interface, or edit production code. Report the exact missing prerequisite and the authorization needed to continue.
- One source read stays one replacement read. Do not hoist or coalesce calls, even when sharing a captured timestamp looks cleaner.
- The requested scope is exhaustive and exclusive. Replace every named call in scope and no adjacent member or file.
- Repository-backed requests require repository work. Start by discovering files from the current workspace. Do not claim the repository is unavailable or ask the user for a path or file contents until workspace-relative discovery found no target. Do not say work was implemented unless the diff proves it.
- Discovered workspace files must be completed in this turn when permitted.
Use a host-native shell reader (
sed/catorGet-Content) only after a confirmed reader availability, transport, or path-normalization failure and only after verifying the canonical path remains inside the current workspace. Stop on content-exclusion, permission/policy, workspace-boundary, or unknown read failures. Use a shell edit fallback only for a confirmed editor availability, transport, or path-normalization failure, never for a stale context, concurrent change, permission/policy denial, or path-boundary error. Before fallback, resolve the canonical path inside the current workspace, freshly read the file, and require an anchored replacement with the expected old text and exact match count; abort if either changed. Then re-open the file, inspect the diff, and validate. Do not ask the user to paste a readable discovered file or report a proposed patch as completed work.
Step 1: Verify prerequisites
Before modifying any code:
- Confirm the wrapper/abstraction exists: Check that the interface or built-in abstraction is available in the project. For
TimeProvider, verify the target framework is .NET 8+ orMicrosoft.Bcl.TimeProvideris referenced. ForSystem.IO.Abstractions, v
Preguntas frecuentes
¿También crea el envoltorio?
No. Si no existe un envoltorio, primero debe crearlo la skill para generar envoltorios de comprobabilidad.
¿Puedo hacer toda la solución de una vez?
La skill trabaja con un alcance acotado, como un archivo, un proyecto o un namespace, para que los cambios se hagan paso a paso.
¿Solo busca las llamadas estáticas?
No. Encontrarlas es tarea de otra skill de detección; esta realiza el reemplazo.
Detalles
Descripción original del autor
ALWAYS USE when asked to migrate, replace, or make testable existing C# static calls with a named wrapper or built-in abstraction: DateTime.UtcNow/Now or DateTimeOffset.UtcNow to TimeProvider/IClock, File.* to IFileSystem or an existing store such as ITextFileStore, and Environment.* to an existing reader such as IEnvironmentReader. Covers scoped files/projects, constructor injection, replacing temp-file or process-environment tests with fakes, "already registered" abstractions, and static classes whose callers/signatures must stay unchanged. Preserves DateTimeKind and call count. DO NOT USE f
repo: dotnet/skills
Popularidad
- Estrellas en GitHub
- 5,8 mil
- Posición en el ranking
- #14632
- Licencia
- MIT
- Actualizada
- 2/11/2026
Comentarios
- …
Más skills de este repositorio
create-custom-agent
5,8 milAyuda a tu agente a crear archivos de agentes personalizados de VS Code, con sus propias herramientas, instrucciones y traspasos a otros agentes.
create-skill
5,8 milAyuda a tu agente a crear una skill nueva de agente con un nombre válido, una descripción de activación clara y un archivo SKILL.md que siga el estándar.
csharp-scripts
5,8 milAyuda a tu agente a ejecutar un pequeño programa en C# como un único archivo con la herramienta de línea de comandos de .NET, sin crear un proyecto completo.
dotnet-pinvoke
5,8 milAyuda a tu agente a llamar correctamente a librerías nativas de C o C++ desde .NET, cubriendo firmas, manejo de cadenas, memoria y handles seguros.
Skills parecidas
test-driven-development
311 milEnseña a tu agente a escribir primero una prueba que falle, verla fallar y después escribir el código más pequeño que la hace pasar, antes de construir cualquier función o corrección.
verification-before-completion
311 milEnseña a tu agente a ejecutar comprobaciones reales y leer su resultado antes de afirmar que una tarea, una corrección o una compilación está completa o en buen estado.
migrate-to-shoehorn
310 milSustituye los casts de tipo arriesgados de tus archivos de prueba por la librería shoehorn, para que las pruebas usen datos parciales y sigan pasando las comprobaciones de tipos.