A real-world strategy for introducing DI into a legacy .NET app: creating a composition root, wrapping statics behind interfaces, bridging the service locator to the container, strangling it incrementally, characterisation tests, and measuring progress.
I'd use a strangler approach, not a rewrite. First, characterisation tests around the code I'll touch first. Then a single composition root (the Generic Host in modern .NET, or ServiceCollection built in the old entry point) and a bridge: the legacy ServiceLocator.Get<T>() delegates to the real IServiceProvider, so old and new code share the same instances.
From there I convert from the edges inwards: new code and any class I touch takes constructor dependencies; statics get thin adapters behind interfaces. I track locator call count as a metric and block new usages with an analyser.
The trade-off: for months the codebase is half old, half new, which is uglier than a rewrite plan but keeps shipping.
"The first rule is not to stop shipping. A big-bang 'introduce DI everywhere' branch in a legacy app never merges. So I'd make DI available first and then let it spread with normal feature work.
For example, at [company] we had [an N-year-old WinForms / ASP.NET MVC 5 / .NET Framework app] with [N] calls to a static
ServiceLocatorand [N] static helpers. I [started by writing characterisation tests around the billing module, because that's where the next features were]. Then I created a composition root: in a modern app that's the Generic Host, in an old one it's aServiceCollectionbuilt inMainorGlobal.asax. The key trick is the bridge: I changedServiceLocator.Get<T>()to call the realIServiceProvider, so every old call site immediately resolves from the container and shares the same singletons as new code. Then any class we touched for a feature got constructor injection, and statics likeConfigHelperandDateTime.Nowgot thin adapters,IOptions<BillingOptions>andTimeProvider. [Over N months, locator calls went from X to Y, and the billing module's test coverage went from A% to B%.]The mistakes I'd avoid: converting static mutable state to a singleton without making it thread-safe, accidentally making something scoped that was really per-call, and letting people add new locator calls while we're removing old ones. I make the locator count a visible metric and add an analyser or architecture test that fails the build on new usages outside the composition root. The goal is not 'zero statics'; pure static helpers like
Mathor string formatting can stay."
| Step | What | Why it comes here |
|---|---|---|
| 1 | Characterisation tests on the first area you'll change | Safety net before moving code |
| 2 | Composition root (Generic Host or ServiceCollection in the entry point) |
One place that owns object creation |
| 3 | Bridge the legacy locator to IServiceProvider |
Old and new code share instances immediately |
| 4 | Adapters for statics with side effects (time, files, config, HTTP) | Creates test seams without touching callers |
| 5 | Constructor injection for new and touched classes | Spreads with normal work |
| 6 | Block new locator usage; track the count | Prevents backsliding |
| 7 | Remove the bridge when the count reaches zero | Finish line |
| Static | Action |
|---|---|
Pure functions (TaxMath.Round) |
Leave static |
| Time, random, file system, environment | Adapter (TimeProvider, IFileStore) |
Config readers (ConfigHelper.Get("X")) |
Options pattern |
| Static caches and mutable state | Thread-safe singleton or IMemoryCache |
| Static DB access | Scoped repository / DbContext |
In a legacy app with around 600 ServiceLocator calls, bridging the locator to the container on day one meant no call site had to change to benefit. Over [nine months] of normal feature work the count fell to under 100, the billing module went from no unit tests to about [70%] coverage, and nothing was ever on a refactoring branch for more than a few days.
Checks the candidate can introduce DI into a real legacy system safely, incrementally and with measurable progress.
Green flags
Red flags
Legacy apps have implicit behaviour: statics initialised in a particular order, singletons that cache per-process, config read at odd times. A rewrite changes all of it at once, and the branch drifts from main within weeks. The strangler fig approach wraps the old system and replaces it piece by piece behind a stable interface.
Before:
OldCode ──▶ ServiceLocator.Get<T>() ──▶ Dictionary<Type, object> (hand-rolled)
After step 3:
OldCode ──▶ ServiceLocator.Get<T>() ──┐
├──▶ IServiceProvider (the real container)
NewCode ──▶ constructor parameters ───┘
Caveat: the locator usually has no notion of scope. Resolving scoped services through it from the root makes them singletons. In web apps, bridge to HttpContext.RequestServices when inside a request (via IHttpContextAccessor) and to the root only for singletons, and enable ValidateScopes to catch mistakes.
// Before: static, untestable
if (DateTime.Now > invoice.DueDate) ...
// After: inject TimeProvider (built into .NET 8+)
if (clock.GetLocalNow() > invoice.DueDate) ...
For static classes you can't change yet, write an instance wrapper (IFileStore over System.IO.File) and inject that into new code. Callers of the static keep working.
ConcurrentDictionary, locks) because the container shares it across requests just like the static did.new of a SqlConnection wrapper → scoped or transient; avoid making it singleton.IDependencyResolver with a scope per request.grep -c or a Roslyn analyser) and publish it on the team dashboard.Microsoft.CodeAnalysis.BannedApiAnalyzers with BannedSymbols.txt) fails the build on new usages outside allowed folders.DateTime.Now and ConfigurationManager.AppSettings; write a characterisation test, then inject TimeProvider and options.ServiceProvider; confirm old and new code get the same singleton.BannedApiAnalyzers with ServiceLocator.Get banned and see the build fail on a new call.Bridging a legacy static locator to the real container, then converting a class.
namespace Legacy.Infrastructure;
// The legacy locator now delegates to the real container (the bridge).
public static class ServiceLocator
{
private static IServiceProvider? _provider;
// Called once from the composition root after Build().
public static void Initialise(IServiceProvider provider) => _provider = provider;
[Obsolete("Use constructor injection. Tracked for removal.")]
public static T Get<T>() where T : notnull =>
(_provider ?? throw new InvalidOperationException("ServiceLocator not initialised"))
.GetRequiredService<T>();
}
// Program.cs: the composition root.
using Legacy.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddOptions<BillingOptions>().BindConfiguration("Billing").ValidateOnStart();
builder.Services.AddSingleton<IExchangeRateCache, ExchangeRateCache>(); // was a static Dictionary
builder.Services.AddScoped<InvoiceService>();
var app = builder.Build();
ServiceLocator.Initialise(app.Services); // old call sites now share the container's singletons
app.Run();
// Before: hidden dependencies through statics.
// public decimal LateFee(Invoice i) =>
// DateTime.Now > i.DueDate ? decimal.Parse(ConfigHelper.Get("LateFee")) : 0m;
// After: touched during a feature, converted to constructor injection.
public sealed class InvoiceService(TimeProvider clock, IOptions<BillingOptions> options)
{
public decimal LateFee(Invoice invoice) =>
clock.GetUtcNow() > invoice.DueDate ? options.Value.LateFee : 0m;
}
public sealed class BillingOptions { public decimal LateFee { get; set; } }
public sealed record Invoice(DateTimeOffset DueDate);
public interface IExchangeRateCache;
public sealed class ExchangeRateCache : IExchangeRateCache; // must be thread-safe: now a shared singleton
DbContext gets shared across concurrent requests and state leaks between users. Instead: only resolve scoped services inside a request scope (HttpContext.RequestServices) or a scope you create per message with IServiceScopeFactory, let the root serve only singletons, and enable ValidateScopes so violations throw.IMemoryCache.ConfigHelper.Get("X") with IConfiguration["X"] everywhere. Why it is wrong: it's still stringly typed and unvalidated. Instead: bind sections to options classes with AddOptions<T>().BindConfiguration(...).ValidateOnStart() and inject IOptions<T> (or IOptionsMonitor<T> if values change at run time).[Obsolete] and banned-API analysers, a composition-root test with ValidateOnBuild, and log the locator's InvalidOperationExceptions with the requested type during the migration.This is as much a change-management problem as a technical one. The team needs to see progress (a falling locator count), have guard rails that stop backsliding, and keep delivering features. I'd write a short ADR that sets the rules (constructor injection for new and touched code, no new locator calls, statics with side effects get adapters) and let the work ride along with features rather than asking for a refactoring budget nobody will approve.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Bridge + incremental conversion | Most legacy apps that must keep shipping | Mixed styles for months | Tiny apps you can convert in a day |
| Big-bang rewrite to DI | Small codebase, strong tests, short freeze acceptable | Delivery stops; high risk | Large, poorly tested systems |
| Leave as is, wrap at the edges | App is near end of life | No improvement inside | App with years of active development ahead |
Inversion of control (IoC) is the broad idea that something else controls the flow and object creation: the framework calls your code, not the other way round. Dependency injection (DI) is a specific IoC technique: a class declares what it needs, usually as constructor parameters, and a caller or container supplies it. The Dependency Inversion Principle (DIP) is the "D" in SOLID: high-level code depends on abstractions it owns, and low-level details implement them.
In ASP.NET Core you register services on builder.Services in Program.cs (the composition root), and the built-in container builds controllers, endpoints and middleware with their dependencies.
The trade-off: DI buys testability and replaceable parts at the cost of indirection; it is a tool, DIP is the design goal.
Singleton guarantees one instance with a global access point. In C# there are three thread-safe ways to write it:
static readonly field: the CLR runs the type initialiser once and thread-safely, so there's no lock to write. Without an explicit static constructor, the runtime may run that initialiser before first use (beforefieldinit), so add one if you need it to happen exactly on first access.Lazy<T>: the factory runs once on first .Value (ExecutionAndPublication by default). It's lazy and correct, which makes it the best choice for an expensive resource that may never be used. The catch is that a failed factory's exception is cached, so a transient failure stays broken until restart.volatile field. It's easy to get wrong, so prefer Lazy<T>.In ASP.NET Core I use services.AddSingleton<T>() instead. It gives one instance per container, constructor injection, disposal of what the container created, and a fake in tests. A static instance is still fine for truly stateless helpers like StringComparer.Ordinal. The trade-off is the same for both: a singleton is shared by every request, so it must be thread-safe and must never capture scoped services.
Good DI makes unit tests container-free: if a class takes its dependencies through the constructor, the test just calls new OrderService(fakeRepo, fakeClock).
For integration tests, WebApplicationFactory<Program> boots the real app and container in memory. In ConfigureTestServices, which runs after Program.cs registrations, you swap external boundaries: services.RemoveAll<IPaymentGateway>(); services.AddSingleton<IPaymentGateway, FakePaymentGateway>();.
Prefer fakes (in-memory implementations, FakeTimeProvider) for state, and mocks only to verify interactions at boundaries.
The trade-off: replacing too much tests your mocks instead of your app; replace only what crosses a process boundary.
How to tell it (STAR)
**S:** At [company] I joined a team maintaining a [10-year-old] billing system with about [600] service-locator calls and almost no tests, and we had to deliver [new invoicing rules] without a freeze. **T:** I proposed introducing DI incrementally so we could test billing changes without slowing delivery. **A:** I wrote characterisation tests around billing, added a composition root and made the old ServiceLocator delegate to the real container so nothing had to change at once. Then every class we touched got constructor injection, statics with side effects got adapters, and I banned new locator calls with an analyser and tracked the count each build. **R:** Over [nine months] locator calls fell from [600] to [under 100], billing coverage went from [near 0] to [70%], manual regression time dropped from [days] to [hours], and the concurrent exchange-rate bug disappeared.
Last updated 23 Nov 2026.