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
- Incremental migration: one project or namespace at a time
When Not to Use
- No wrapper or abstraction exists yet (use
generate-testability-wrappers first)
- The user wants to detect statics, not migrate them (use
detect-static-dependencies)
- The code does not use dependency injection and the user hasn't chosen ambient context
- Migrating between test frameworks (use the appropriate migration skill)
Inputs
| Input |
Required |
Description |
| Static pattern |
Yes |
What to replace (e.g., DateTime.UtcNow, File.ReadAllText) |
| Replacement abstraction |
Yes |
What to use instead (e.g., TimeProvider, IFileSystem) |
| Scope |
Yes |
File path, project (.csproj), namespace, or directory to migrate |
| Injection strategy |
No |
constructor (default), primary-constructor, or ambient |
Workflow
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+ or Microsoft.Bcl.TimeProvider is referenced. For System.IO.Abstractions, verify the NuGet package is referenced.
Confirm DI registration exists: Check Program.cs or Startup.cs for the service registration. If missing, add it before proceeding.
Identify all files in scope: List the .cs files that will be modified. Exclude test projects, obj/, bin/, and generated code.
Step 2: Plan the migration for each file
For each file containing the static pattern, determine:
- Which class(es) contain the call sites — identify the class declarations
- Whether the class already has the dependency injected — check constructors for existing
TimeProvider, IFileSystem, etc. parameters
- The replacement expression for each call site
Replacement mapping
| 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 a DateTimeOffset. Converting back to DateTime must keep the original Kind, otherwise you introduce a behavioral change even though the code still compiles:
DateTime.UtcNow has Kind == Utc → use .UtcDateTime (not .DateTime, which yields Kind == Unspecified).
DateTime.Now has Kind == Local → use .LocalDateTime (not .DateTime).
- When a call site consumes a
DateTimeOffset directly (a field/parameter/return already typed DateTimeOffset), drop the .UtcDateTime/.LocalDateTime suffix and assign the DateTimeOffset as-is — don't force it back through DateTime.
Match the target member's type: if the surrounding field/property is DateTime, keep it DateTime (via the Kind-correct property above); do not change it to DateTimeOffset as part of a "mechanical" migration — that is a design change, not a delegation.
Step 3: Add constructor injection
Add the new dependency following the class's existing pattern:
- Primary constructor (C# 12+): Add parameter to primary constructor:
public class OrderProcessor(ILogger<OrderProcessor> logger, TimeProvider timeProvider)
- Traditional constructor: Add
private readonly field + constructor parameter, matching the existing field naming convention (_camelCase or m_camelCase)
Static classes: use ambient context (no constructor injection)
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 the ambient context pattern: expose a static, settable seam that defaults to the real implementation and is overridden once at composition/test setup.
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.
public static class TimestampFormatter
{
// Ambient seam — defaults to the real clock, swap in tests.
public static TimeProvider Clock { get; set; } = TimeProvider.System;
public static string Now() => Clock.GetUtcNow().ToString("O");
}
Production: leave Clock at its TimeProvider.System default, or assign the DI-resolved TimeProvider once at startup (TimestampFormatter.Clock = app.Services.GetRequiredService<TimeProvider>();).
Tests: override Clock with a FakeTimeProvider and always restore it in a finally so a failing assertion can't leak the fake into other tests:
var original = TimestampFormatter.Clock;
TimestampFormatter.Clock = new FakeTimeProvider(instant);
try
{
// exercise code under test
}
finally
{
TimestampFormatter.Clock = original;
}
Parallelism caveat: a mutable static seam is process-global. Tests that mutate it must not run in parallel with each other (or with code that reads it) — put them in a non-parallel collection/class (e.g. xUnit [Collection] with parallelization disabled, or MSTest [DoNotParallelize]). Only if the class is not required to stay static and its tests must run fully parallel should you consider converting the caller to an instance with constructor injection instead — otherwise keep the ambient seam.
The same seam works for other statics (IFileSystem, custom wrappers): a public static <Abstraction> X { get; set; } defaulting to the real implementation, with the same restore-in-finally and non-parallel discipline.
Step 4: Replace call sites
Perform each replacement mechanically. For each call site:
- Replace the static call with the wrapper call
- Preserve the surrounding code structure (whitespace, comments, chaining)
- Add required
using directives if not already present
Adding using directives
| 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>; |
Step 5: Update affected test files
If test files exist for the migrated classes:
- Update constructor calls — add the new parameter to test class instantiation
- Use test doubles:
TimeProvider → new FakeTimeProvider() from Microsoft.Extensions.TimeProvider.Testing
IFileSystem → new MockFileSystem() from System.IO.Abstractions.TestingHelpers
- Custom wrappers →
new Mock<IWrapperName>() or hand-rolled fake
Step 6: Build verification
After all changes in the current scope:
dotnet build <project.csproj>
If the build fails:
- Missing using: Add the required
using directive
- Missing NuGet package: Run
dotnet add package <name>
- Constructor mismatch in tests: Update test instantiation (Step 5)
- Ambiguous call: Fully qualify the wrapper call
Step 7: Report changes
Summarize what was done:
## 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)
Validation
Common Pitfalls
| 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. |
| Migrating too much at once |
Stick to the defined scope — one project or namespace per run |
| Forgetting DI registration |
Always verify Program.cs/Startup.cs has the registration before replacing call sites |
1---2name: migrate-static-to-wrapper3description: >4 Replace existing static dependency call sites with a wrapper or built-in5 abstraction that already exists or is registered in DI. Codemod-style bulk6 replacement of DateTime.Now/UtcNow to TimeProvider, File.ReadAllText to7 IFileSystem, and similar, across a bounded scope (file, project, namespace),8 adding constructor injection to affected classes and updating their unit tests9 to use a test double.10 USE FOR: replace DateTime.UtcNow/DateTime.Now with TimeProvider and add the11 constructor parameter, migrate static call sites to a wrapper already in DI,12 bulk replace File.* with IFileSystem, scoped migration of statics in only13 certain files, migrate a service to TimeProvider and update its unit tests to a14 controllable/fake time source, update test doubles when migrating off static15 DateTime/File calls.16 DO NOT USE FOR: detecting statics (use detect-static-dependencies), creating or17 registering the wrapper when it does not exist yet (use18 generate-testability-wrappers), migrating between test frameworks.19license: MIT20metadata:21 source: https://skillmd.com/skills/stanfish06/migrate-static-to-wrapper22---2324# Migrate Static to Wrapper2526Perform 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.2728## When to Use2930- After wrappers have been generated (via `generate-testability-wrappers`) or built-in abstractions identified31- Migrating `DateTime.UtcNow` → `TimeProvider.GetUtcNow()` across a project32- Migrating `File.*` → `IFileSystem.File.*` across a namespace33- Adding constructor injection for the new abstraction to affected classes34- Incremental migration: one project or namespace at a time3536## When Not to Use3738- No wrapper or abstraction exists yet (use `generate-testability-wrappers` first)39- The user wants to detect statics, not migrate them (use `detect-static-dependencies`)40- The code does not use dependency injection and the user hasn't chosen ambient context41- Migrating between test frameworks (use the appropriate migration skill)4243## Inputs4445| Input | Required | Description |46|-------|----------|-------------|47| Static pattern | Yes | What to replace (e.g., `DateTime.UtcNow`, `File.ReadAllText`) |48| Replacement abstraction | Yes | What to use instead (e.g., `TimeProvider`, `IFileSystem`) |49| Scope | Yes | File path, project (.csproj), namespace, or directory to migrate |50| Injection strategy | No | `constructor` (default), `primary-constructor`, or `ambient` |5152## Workflow5354### Step 1: Verify prerequisites5556Before modifying any code:57581. **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.59602. **Confirm DI registration exists**: Check `Program.cs` or `Startup.cs` for the service registration. If missing, add it before proceeding.61623. **Identify all files in scope**: List the `.cs` files that will be modified. Exclude test projects, `obj/`, `bin/`, and generated code.6364### Step 2: Plan the migration for each file6566For each file containing the static pattern, determine:67681. **Which class(es) contain the call sites** — identify the class declarations692. **Whether the class already has the dependency injected** — check constructors for existing `TimeProvider`, `IFileSystem`, etc. parameters703. **The replacement expression** for each call site7172#### Replacement mapping7374| Category | Original | DI replacement |75|----------|----------|----------------|76| Time | `DateTime.Now` | `_timeProvider.GetLocalNow().LocalDateTime` |77| Time | `DateTime.UtcNow` | `_timeProvider.GetUtcNow().UtcDateTime` |78| Time | `DateTime.Today` | `_timeProvider.GetLocalNow().LocalDateTime.Date` |79| Time | `DateTimeOffset.Now` | `_timeProvider.GetLocalNow()` |80| Time | `DateTimeOffset.UtcNow` | `_timeProvider.GetUtcNow()` |81| File | `File.ReadAllText(path)` | `_fileSystem.File.ReadAllText(path)` |82| File | `File.WriteAllText(path, text)` | `_fileSystem.File.WriteAllText(path, text)` |83| File | `File.Exists(path)` | `_fileSystem.File.Exists(path)` |84| File | `Directory.Exists(path)` | `_fileSystem.Directory.Exists(path)` |85| Env | `Environment.GetEnvironmentVariable(name)` | `_env.GetEnvironmentVariable(name)` |86| Console | `Console.WriteLine(msg)` | `_console.WriteLine(msg)` |87| Process | `Process.Start(info)` | `_processRunner.Start(info)` |8889Apply the same pattern for other members in each category.9091> **Preserve `DateTimeKind` — this is the most common silent regression.** `TimeProvider.GetUtcNow()` / `GetLocalNow()` return a `DateTimeOffset`. Converting back to `DateTime` **must keep the original `Kind`**, otherwise you introduce a behavioral change even though the code still compiles:92>93> - `DateTime.UtcNow` has `Kind == Utc` → use `.UtcDateTime` (**not** `.DateTime`, which yields `Kind == Unspecified`).94> - `DateTime.Now` has `Kind == Local` → use `.LocalDateTime` (**not** `.DateTime`).95> - When a call site consumes a `DateTimeOffset` directly (a field/parameter/return already typed `DateTimeOffset`), drop the `.UtcDateTime`/`.LocalDateTime` suffix and assign the `DateTimeOffset` as-is — don't force it back through `DateTime`.96>97> Match the **target member's type**: if the surrounding field/property is `DateTime`, keep it `DateTime` (via the Kind-correct property above); do not change it to `DateTimeOffset` as part of a "mechanical" migration — that is a design change, not a delegation.9899### Step 3: Add constructor injection100101Add the new dependency following the class's existing pattern:102103- **Primary constructor** (C# 12+): Add parameter to primary constructor: `public class OrderProcessor(ILogger<OrderProcessor> logger, TimeProvider timeProvider)`104- **Traditional constructor**: Add `private readonly` field + constructor parameter, matching the existing field naming convention (`_camelCase` or `m_camelCase`)105106#### Static classes: use ambient context (no constructor injection)107108A `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 the **ambient context** pattern: expose a static, settable seam that defaults to the real implementation and is overridden once at composition/test setup.109110When 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.111112```csharp113public static class TimestampFormatter114{115 // Ambient seam — defaults to the real clock, swap in tests.116 public static TimeProvider Clock { get; set; } = TimeProvider.System;117118 public static string Now() => Clock.GetUtcNow().ToString("O");119}120```121122- Production: leave `Clock` at its `TimeProvider.System` default, or assign the DI-resolved `TimeProvider` once at startup (`TimestampFormatter.Clock = app.Services.GetRequiredService<TimeProvider>();`).123- Tests: override `Clock` with a `FakeTimeProvider` and **always restore it in a `finally`** so a failing assertion can't leak the fake into other tests:124125 ```csharp126 var original = TimestampFormatter.Clock;127 TimestampFormatter.Clock = new FakeTimeProvider(instant);128 try129 {130 // exercise code under test131 }132 finally133 {134 TimestampFormatter.Clock = original;135 }136 ```137138- **Parallelism caveat**: a mutable static seam is process-global. Tests that mutate it must **not** run in parallel with each other (or with code that reads it) — put them in a non-parallel collection/class (e.g. xUnit `[Collection]` with parallelization disabled, or MSTest `[DoNotParallelize]`). Only if the class is *not* required to stay static and its tests must run fully parallel should you consider converting the caller to an instance with constructor injection instead — otherwise keep the ambient seam.139- The same seam works for other statics (`IFileSystem`, custom wrappers): a `public static <Abstraction> X { get; set; }` defaulting to the real implementation, with the same restore-in-`finally` and non-parallel discipline.140141### Step 4: Replace call sites142143Perform each replacement mechanically. For each call site:1441451. Replace the static call with the wrapper call1462. Preserve the surrounding code structure (whitespace, comments, chaining)1473. Add required `using` directives if not already present148149#### Adding using directives150151| Abstraction | Using directive |152|------------|-----------------|153| `TimeProvider` | None (in `System` namespace) |154| `IFileSystem` | `using System.IO.Abstractions;` |155| `IHttpClientFactory` | `using System.Net.Http;` (usually already present) |156| Custom wrappers | `using <wrapper namespace>;` |157158### Step 5: Update affected test files159160If test files exist for the migrated classes:1611621. **Update constructor calls** — add the new parameter to test class instantiation1632. **Use test doubles**:164 - `TimeProvider` → `new FakeTimeProvider()` from `Microsoft.Extensions.TimeProvider.Testing`165 - `IFileSystem` → `new MockFileSystem()` from `System.IO.Abstractions.TestingHelpers`166 - Custom wrappers → `new Mock<IWrapperName>()` or hand-rolled fake167168### Step 6: Build verification169170After all changes in the current scope:171172```bash173dotnet build <project.csproj>174```175176If the build fails:177- **Missing using**: Add the required `using` directive178- **Missing NuGet package**: Run `dotnet add package <name>`179- **Constructor mismatch in tests**: Update test instantiation (Step 5)180- **Ambiguous call**: Fully qualify the wrapper call181182### Step 7: Report changes183184Summarize what was done:185186```187## Migration Summary188189**Pattern**: DateTime.UtcNow → TimeProvider.GetUtcNow()190**Scope**: MyProject/Services/191192### Files Modified (production)193| File | Call Sites Replaced | Injection Added |194|------|--------------------:|:----------------|195| OrderProcessor.cs | 3 | Yes (constructor) |196| NotificationService.cs | 1 | Yes (primary ctor) |197198### Files Modified (tests)199| File | Change |200|------|--------|201| OrderProcessorTests.cs | Added FakeTimeProvider parameter |202203### Remaining (out of scope)204- MyProject/Legacy/ — 8 call sites not migrated (different namespace)205```206207## Validation208209- [ ] All call sites in scope were replaced (none missed)210- [ ] Constructor injection added to all affected classes211- [ ] Field naming follows existing class conventions212- [ ] Required `using` directives added213- [ ] Required NuGet packages referenced214- [ ] Build succeeds after migration215- [ ] Test files updated with appropriate test doubles216- [ ] No behavioral changes introduced (wrapper delegates directly to the static)217- [ ] `DateTimeKind` preserved — former `DateTime.UtcNow` stays `Utc` (`.UtcDateTime`), former `DateTime.Now` stays `Local` (`.LocalDateTime`)218219## Common Pitfalls220221| Pitfall | Solution |222|---------|----------|223| Replacing statics in test code | Only replace in production code; tests should use fakes/mocks |224| Breaking static classes | Static classes can't have constructors — use the ambient context seam (Step 3) instead of converting them to non-static |225| Missing `FakeTimeProvider` NuGet | Add `Microsoft.Extensions.TimeProvider.Testing` to test project |226| 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. |227| Migrating too much at once | Stick to the defined scope — one project or namespace per run |228| Forgetting DI registration | Always verify `Program.cs`/`Startup.cs` has the registration before replacing call sites |