npx skills add ...
npx skills add dotnet/skills --skill migrate-static-to-wrapper
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 for finding statics (detect-static-dependencies), choosing/designing a new wrapper (generate-testability-wrappers), behavior tests with no chosen seam (testability-obstacle), or test-framework migration.
npx skills add dotnet/skills --skill 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.
generate-testability-wrappers) or built-in abstractions identifiedDateTime.UtcNow → TimeProvider.GetUtcNow() across a projectFile.* → IFileSystem.File.* across a namespacestatic utility class testable by adding an ambient seam (Step 3) while its existing call sites keep
compiling unchangedgenerate-testability-wrappers first).
A built-in abstraction such as TimeProvider or IFileSystem always counts as existing.detect-static-dependencies)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.
| 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 |
sed/cat or Get-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.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+ or Microsoft.Bcl.TimeProvider is referenced. For System.IO.Abstractions, verify the NuGet package is referenced. A package that could provide an abstraction is not the same as an abstraction already available to this project.
Confirm production composition exists: Check Program.cs, Startup.cs, or manual construction sites. If package, wrapper, or registration work is missing, add it only when the user explicitly authorized those dependency/composition changes. Otherwise stop before editing call sites and report the exact prerequisite; do not turn a scoped migration into first-time abstraction design.
Identify all files in scope: List the .cs files that will be modified. Exclude test projects, obj/, bin/, and generated code.
Lock and count the member set before editing: Use the exact member named by the user, or infer the smallest unambiguous set from the request and discovered call sites. Record that set, then search every member and capture the file/line inventory. Do not change the set mid-edit or infer counts from a partial read.
Migrate exactly what was asked — nothing adjacent. If the user named a member (DateTime.UtcNow), migrate only that member and leave siblings such as DateTime.Now untouched. If the user named files, do not touch other files. Preserve a call site whose comment or name marks it as deliberate (e.g. // intentional local time) unless the user explicitly names that site and requests a semantics-preserving migration. List everything you deliberately left alone under "Remaining (out of scope)" so the user can ask for it in a follow-up; suggesting is fine, silently widening the scope is not.
For each file containing the static pattern, determine:
TimeProvider, IFileSystem, etc. parameters| Category | Original | DI replacement |
|---|---|---|
| Time | DateTime.Now | _timeProvider.GetLocalNow().LocalDateTime |
| Time | DateTime.UtcNow | _timeProvider.GetUtcNow().UtcDateTime |
| Time | DateTime.Today | _timeProvider.GetLocalNow().LocalDateTime.Date |
| Time | DateTimeOffset.Now | _timeProvider.GetLocalNow() |
| Time | DateTimeOffset.UtcNow | _timeProvider.GetUtcNow() |
| File | File.ReadAllText(path) | _fileSystem.File.ReadAllText(path) |
| File | File.WriteAllText(path, text) | _fileSystem.File.WriteAllText(path, text) |
| File | File.Exists(path) | _fileSystem.File.Exists(path) |
| File | Directory.Exists(path) | _fileSystem.Directory.Exists(path) |
| Env | Environment.GetEnvironmentVariable(name) | _env.GetEnvironmentVariable(name) |
| Console | Console.WriteLine(msg) | _console.WriteLine(msg) |
| Process | Process.Start(info) | _processRunner.Start(info) |
Apply the same pattern for other members in each category.
Preserve
DateTimeKind— this is the most common silent regression.TimeProvider.GetUtcNow()/GetLocalNow()return aDateTimeOffset. Converting back toDateTimemust keep the originalKind, otherwise you introduce a behavioral change even though the code still compiles:
DateTime.UtcNowhasKind == Utc→ use.UtcDateTime(not.DateTime, which yieldsKind == Unspecified).DateTime.NowhasKind == Local→ use.LocalDateTime(not.DateTime).- When a call site consumes a
DateTimeOffsetdirectly (a field/parameter/return already typedDateTimeOffset), drop the.UtcDateTime/.LocalDateTimesuffix and assign theDateTimeOffsetas-is — don't force it back throughDateTime.Match the target member's type: if the surrounding field/property is
DateTime, keep itDateTime(via the Kind-correct property above); do not change it toDateTimeOffsetas part of a "mechanical" migration — that is a design change, not a delegation.Preserve the number, order, and location of reads as well as the value type. Replace each original clock read in place with one provider read. Do not hoist, cache, or coalesce two reads into a shared
nowlocal, even when they are in the same object initializer or method. Two consecutiveDateTime.UtcNowcalls could observe different instants; makingCreatedAtandExpiresAtderive from one captured value is a behavior change, not a mechanical migration. Reuse a value only when the original code already captured and reused one.
Add the new dependency following the class's existing pattern:
public class OrderProcessor(ILogger<OrderProcessor> logger, TimeProvider timeProvider)private readonly field + constructor parameter, matching the existing field naming convention (_camelCase or m_camelCase)A static class with only static members cannot receive constructor injection — adding an instance constructor or instance field would break it. Do not convert it to a non-static class just to inject the dependency; that changes its design and every call site. Instead, apply a scoped ambient seam that defaults to the real implementation and can be overridden without leaking process-global state.
When the user wants to keep the class static, the ambient seam below is the answer — present it as the solution and implement it directly. Do not hedge by offering "convert it to a non-static class" or "pass TimeProvider as a method parameter" as co-equal alternatives; those change the class's design or public API and are not what was asked. Lead with the seam, then note the parallelism trade-off.
TimeProvider.System whenever no override is active; no startup mutation is required.AsyncLocal<T> keeps independently established test flows isolated across await. Do not store a mutable stack/list in the slot or mutate one fake inherited by multiple child flows.IFileSystem, custom wrappers): store the abstraction value in AsyncLocal<T>, default to the real implementation, and restore the previous value from the scope.Perform each replacement mechanically. For each call site:
using directives if not already presentAfter editing, repeat the exact search and require zero occurrences in every in-scope production file. Re-open each changed file and compare the result to the pre-edit inventory. A summary count is not evidence if one method was silently missed.
Also verify the exclusive side of the scope: search or compare every file the
user explicitly said to leave alone and require its original static calls and
content to remain. For a single-file migration, report both numbers even when
they are small: N/N in-scope calls replaced and M named out-of-scope calls
preserved.
| Abstraction | Using directive |
|---|---|
TimeProvider | None (in System namespace) |
IFileSystem | using System.IO.Abstractions; |
IHttpClientFactory | using System.Net.Http; (usually already present) |
| Custom wrappers | using <wrapper namespace>; |
If test files exist for the migrated classes:
TimeProvider → new FakeTimeProvider() from Microsoft.Extensions.TimeProvider.TestingIFileSystem → new MockFileSystem() from System.IO.Abstractions.TestingHelpersnew Mock<IWrapperName>() or hand-rolled fakePreserve every observable branch that depended on the original static result. For
example, migrating Environment.GetEnvironmentVariable(name) ?? "production"
requires tests for both a configured value and null/missing input selecting the
fallback. A fake-only happy path is not enough to prove a mechanical migration.
When tests already exist, preserve their framework and assertion style, but make
the replacement dependency observable: include at least one configured/fake
value assertion and one fallback or error-path assertion where the original
static API exposed both outcomes. Merely making the old tests compile is not
complete migration evidence.
When the request explicitly converts affected unit tests away from real file or environment access, prove those tests no longer touch the process-global dependency: search them for temp-file, real-disk, or environment-mutation APIs after editing. Preserve intentional integration tests outside that requested scope. Report the deterministic fake's configured and fallback/error cases rather than only saying that a fake was added.
After all changes in the current scope, build the affected production project and run the narrowest affected test project whenever tests exist or were changed:
Report the build result you actually observed. Only write "build succeeded" when the command exited 0; if it failed — including restore/NuGet failures such as "assets file not found" — say so, quote the error, and either fix it (dotnet restore, add the missing package) or hand the user a precise blocker. A false success claim is worse than an unfinished migration.
If the build fails:
using directiveDo not substitute a successful build for the requested test run. When migration changes constructor calls, fakes, process-global state, or real I/O, only the targeted tests prove the complete path. If the test command is blocked, report that blocker rather than claiming the migration is fully validated.
Summarize what was done. Even for one production file and one test file, include the exact in-scope replacement count, the named out-of-scope files or calls verified unchanged, and the targeted build/test result:
using directives addedDateTimeKind preserved — former DateTime.UtcNow stays Utc (.UtcDateTime), former DateTime.Now stays Local (.LocalDateTime)| Pitfall | Solution |
|---|---|
| Replacing statics in test code | Only replace in production code; tests should use fakes/mocks |
| Breaking static classes | Static classes can't have constructors — use the ambient context seam (Step 3) instead of converting them to non-static |
Missing FakeTimeProvider NuGet | Add Microsoft.Extensions.TimeProvider.Testing to test project |
Replacing a DateTime value with .DateTime off a DateTimeOffset | DateTimeOffset.DateTime returns Kind == Unspecified — use .UtcDateTime (for former DateTime.UtcNow) or .LocalDateTime (for former DateTime.Now) to preserve the original DateTimeKind. Only change the field/return type to DateTimeOffset if the user asked for it. |
| Capturing one provider value for multiple original clock reads | Replace each read in place. Coalescing reads changes observable timing even when it looks cleaner. |
| Migrating too much at once | Stick to the defined scope — one project or namespace per run |
Migrating DateTime.Now when only UtcNow was requested | Respect the literal request; list the other call sites as out-of-scope suggestions instead of rewriting them |
| Claiming "Build succeeded" after a failed restore | Read the exit code and output; report the real failure and fix it or surface it as a blocker |
| Adding a package during a call-site-only migration | Stop and request authorization or run wrapper/adoption setup first |
| Forgetting production composition | Verify DI registration, manual construction, or the ambient production default before replacing call sites |
dotnet build <project.csproj>
dotnet test <affected-test-project.csproj>## Migration Summary
**Pattern**: DateTime.UtcNow → TimeProvider.GetUtcNow()
**Scope**: MyProject/Services/
### Files Modified (production)
| File | Call Sites Replaced | Injection Added |
|------|--------------------:|:----------------|
| OrderProcessor.cs | 3 | Yes (constructor) |
| NotificationService.cs | 1 | Yes (primary ctor) |
### Files Modified (tests)
| File | Change |
|------|--------|
| OrderProcessorTests.cs | Added FakeTimeProvider parameter |
### Remaining (out of scope)
- MyProject/Legacy/ — 8 call sites not migrated (different namespace)