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().DateTime |
| Time |
DateTime.UtcNow |
_timeProvider.GetUtcNow().DateTime |
| Time |
DateTime.Today |
_timeProvider.GetLocalNow().Date |
| 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.
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)
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 ambient context for these |
Missing FakeTimeProvider NuGet |
Add Microsoft.Extensions.TimeProvider.Testing to test project |
| Replacing in expression-bodied members without updating return type |
DateTime → DateTimeOffset when using TimeProvider.GetUtcNow() — verify type compatibility |
| 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 wrapper or built-in5 abstraction calls when the abstraction already exists or is already registered6 in DI. Codemod-style bulk replacement of DateTime.Now/UtcNow to TimeProvider,7 File.ReadAllText to IFileSystem, and similar, across a bounded scope (file,8 project, or namespace). Adds the constructor injection parameter to affected classes.9 USE FOR: replace all DateTime.UtcNow/DateTime.Now calls with TimeProvider and add10 the constructor parameter, TimeProvider already registered in DI so migrate the call11 sites, migrate static calls to wrapper, bulk replace File.* with IFileSystem, codemod12 static to injectable, add constructor injection for an existing dependency, scoped13 migration of statics, migrate statics in only certain scoped files.14 DO NOT USE FOR: detecting statics (use detect-static-dependencies), creating the15 wrapper or registering it when it does not exist yet (use16 generate-testability-wrappers), migrating between test frameworks.17license: MIT18metadata:19 source: https://skillmd.com/skills/dotnet/migrate-static-to-wrapper20---2122# Migrate Static to Wrapper2324Perform 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.2526## When to Use2728- After wrappers have been generated (via `generate-testability-wrappers`) or built-in abstractions identified29- Migrating `DateTime.UtcNow` → `TimeProvider.GetUtcNow()` across a project30- Migrating `File.*` → `IFileSystem.File.*` across a namespace31- Adding constructor injection for the new abstraction to affected classes32- Incremental migration: one project or namespace at a time3334## When Not to Use3536- No wrapper or abstraction exists yet (use `generate-testability-wrappers` first)37- The user wants to detect statics, not migrate them (use `detect-static-dependencies`)38- The code does not use dependency injection and the user hasn't chosen ambient context39- Migrating between test frameworks (use the appropriate migration skill)4041## Inputs4243| Input | Required | Description |44|-------|----------|-------------|45| Static pattern | Yes | What to replace (e.g., `DateTime.UtcNow`, `File.ReadAllText`) |46| Replacement abstraction | Yes | What to use instead (e.g., `TimeProvider`, `IFileSystem`) |47| Scope | Yes | File path, project (.csproj), namespace, or directory to migrate |48| Injection strategy | No | `constructor` (default), `primary-constructor`, or `ambient` |4950## Workflow5152### Step 1: Verify prerequisites5354Before modifying any code:55561. **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.57582. **Confirm DI registration exists**: Check `Program.cs` or `Startup.cs` for the service registration. If missing, add it before proceeding.59603. **Identify all files in scope**: List the `.cs` files that will be modified. Exclude test projects, `obj/`, `bin/`, and generated code.6162### Step 2: Plan the migration for each file6364For each file containing the static pattern, determine:65661. **Which class(es) contain the call sites** — identify the class declarations672. **Whether the class already has the dependency injected** — check constructors for existing `TimeProvider`, `IFileSystem`, etc. parameters683. **The replacement expression** for each call site6970#### Replacement mapping7172| Category | Original | DI replacement |73|----------|----------|----------------|74| Time | `DateTime.Now` | `_timeProvider.GetLocalNow().DateTime` |75| Time | `DateTime.UtcNow` | `_timeProvider.GetUtcNow().DateTime` |76| Time | `DateTime.Today` | `_timeProvider.GetLocalNow().Date` |77| Time | `DateTimeOffset.UtcNow` | `_timeProvider.GetUtcNow()` |78| File | `File.ReadAllText(path)` | `_fileSystem.File.ReadAllText(path)` |79| File | `File.WriteAllText(path, text)` | `_fileSystem.File.WriteAllText(path, text)` |80| File | `File.Exists(path)` | `_fileSystem.File.Exists(path)` |81| File | `Directory.Exists(path)` | `_fileSystem.Directory.Exists(path)` |82| Env | `Environment.GetEnvironmentVariable(name)` | `_env.GetEnvironmentVariable(name)` |83| Console | `Console.WriteLine(msg)` | `_console.WriteLine(msg)` |84| Process | `Process.Start(info)` | `_processRunner.Start(info)` |8586Apply the same pattern for other members in each category.8788### Step 3: Add constructor injection8990Add the new dependency following the class's existing pattern:9192- **Primary constructor** (C# 12+): Add parameter to primary constructor: `public class OrderProcessor(ILogger<OrderProcessor> logger, TimeProvider timeProvider)`93- **Traditional constructor**: Add `private readonly` field + constructor parameter, matching the existing field naming convention (`_camelCase` or `m_camelCase`)9495#### Static classes: use ambient context (no constructor injection)9697A `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.9899```csharp100public static class TimestampFormatter101{102 // Ambient seam — defaults to the real clock, swap in tests.103 public static TimeProvider Clock { get; set; } = TimeProvider.System;104105 public static string Now() => Clock.GetUtcNow().ToString("O");106}107```108109- Production: leave `Clock` at its `TimeProvider.System` default, or assign the DI-resolved `TimeProvider` once at startup (`TimestampFormatter.Clock = app.Services.GetRequiredService<TimeProvider>();`).110- 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:111112 ```csharp113 var original = TimestampFormatter.Clock;114 TimestampFormatter.Clock = new FakeTimeProvider(instant);115 try116 {117 // exercise code under test118 }119 finally120 {121 TimestampFormatter.Clock = original;122 }123 ```124125- **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]`). If tests must run in parallel, prefer constructor injection (convert the caller) over an ambient static.126- 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.127128### Step 4: Replace call sites129130Perform each replacement mechanically. For each call site:1311321. Replace the static call with the wrapper call1332. Preserve the surrounding code structure (whitespace, comments, chaining)1343. Add required `using` directives if not already present135136#### Adding using directives137138| Abstraction | Using directive |139|------------|-----------------|140| `TimeProvider` | None (in `System` namespace) |141| `IFileSystem` | `using System.IO.Abstractions;` |142| `IHttpClientFactory` | `using System.Net.Http;` (usually already present) |143| Custom wrappers | `using <wrapper namespace>;` |144145### Step 5: Update affected test files146147If test files exist for the migrated classes:1481491. **Update constructor calls** — add the new parameter to test class instantiation1502. **Use test doubles**:151 - `TimeProvider` → `new FakeTimeProvider()` from `Microsoft.Extensions.TimeProvider.Testing`152 - `IFileSystem` → `new MockFileSystem()` from `System.IO.Abstractions.TestingHelpers`153 - Custom wrappers → `new Mock<IWrapperName>()` or hand-rolled fake154155### Step 6: Build verification156157After all changes in the current scope:158159```bash160dotnet build <project.csproj>161```162163If the build fails:164- **Missing using**: Add the required `using` directive165- **Missing NuGet package**: Run `dotnet add package <name>`166- **Constructor mismatch in tests**: Update test instantiation (Step 5)167- **Ambiguous call**: Fully qualify the wrapper call168169### Step 7: Report changes170171Summarize what was done:172173```174## Migration Summary175176**Pattern**: DateTime.UtcNow → TimeProvider.GetUtcNow()177**Scope**: MyProject/Services/178179### Files Modified (production)180| File | Call Sites Replaced | Injection Added |181|------|--------------------:|:----------------|182| OrderProcessor.cs | 3 | Yes (constructor) |183| NotificationService.cs | 1 | Yes (primary ctor) |184185### Files Modified (tests)186| File | Change |187|------|--------|188| OrderProcessorTests.cs | Added FakeTimeProvider parameter |189190### Remaining (out of scope)191- MyProject/Legacy/ — 8 call sites not migrated (different namespace)192```193194## Validation195196- [ ] All call sites in scope were replaced (none missed)197- [ ] Constructor injection added to all affected classes198- [ ] Field naming follows existing class conventions199- [ ] Required `using` directives added200- [ ] Required NuGet packages referenced201- [ ] Build succeeds after migration202- [ ] Test files updated with appropriate test doubles203- [ ] No behavioral changes introduced (wrapper delegates directly to the static)204205## Common Pitfalls206207| Pitfall | Solution |208|---------|----------|209| Replacing statics in test code | Only replace in production code; tests should use fakes/mocks |210| Breaking static classes | Static classes can't have constructors — use the ambient context seam (Step 3) instead of converting them to non-static |211| Missing `FakeTimeProvider` NuGet | Add `Microsoft.Extensions.TimeProvider.Testing` to test project |212| Replacing in expression-bodied members without updating return type | `DateTime` → `DateTimeOffset` when using `TimeProvider.GetUtcNow()` — verify type compatibility |213| Migrating too much at once | Stick to the defined scope — one project or namespace per run |214| Forgetting DI registration | Always verify `Program.cs`/`Startup.cs` has the registration before replacing call sites |