📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You join a team with a large legacy .NET application full of static helper classes, a hand-rolled ServiceLocator.Get<T>() and singletons that read configuration directly. How would you introduce dependency injection without a big-bang rewrite? Explain the composition root, the order you would tackle things in, and how you would keep the app shippable throughout.

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.

Senior RealWorldScenario Advanced composition-root dependency-injection legacy-code refactoring service-locator strangler-fig

🎯 Key points

  • Start with characterisation tests around the area you will change first
  • Create one composition root with the Generic Host (WebApplication/Host.CreateApplicationBuilder on .NET 10, or ServiceCollection in a .NET Framework entry point)
  • Bridge: make the legacy ServiceLocator delegate to the real IServiceProvider so old and new code share instances
  • Scoped services must only be resolved from a request or message scope, never from the root via the locator; enable ValidateScopes
  • Wrap statics behind interfaces with thin adapters (TimeProvider over DateTime.Now, IFileStore over File.*, IOptions<T> over ConfigHelper)
  • Convert from the edges inwards: new code and touched code take constructor dependencies; leave untouched code alone
  • Track locator call count as a metric and block new usages with an analyser or architecture test
  • Ship every step; no long-lived refactoring branch

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 ServiceLocator and [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 a ServiceCollection built in Main or Global.asax. The key trick is the bridge: I changed ServiceLocator.Get<T>() to call the real IServiceProvider, 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 like ConfigHelper and DateTime.Now got thin adapters, IOptions<BillingOptions> and TimeProvider. [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 Math or string formatting can stay."


The sequence

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

What to convert, what to leave

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

Production example

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.

🔍 What the interviewer is checking

Checks the candidate can introduce DI into a real legacy system safely, incrementally and with measurable progress.

Green flags

  • Rejects big-bang; uses characterisation tests and a strangler approach
  • Bridges the old locator to the real container
  • Handles lifetimes and thread safety deliberately
  • Measures progress and blocks new locator usage

Red flags

  • "Rewrite it all with DI"
  • Ignores scoped services resolved from the root
  • Converts pure static helpers just for consistency

📚 Learn in depth

1. Why big-bang fails

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.

2. The bridge

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.

3. Adapters for statics

// 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.

4. Lifetimes during migration

  • Static mutable state → singleton, but make it thread-safe (ConcurrentDictionary, locks) because the container shares it across requests just like the static did.
  • Per-call new of a SqlConnection wrapper → scoped or transient; avoid making it singleton.
  • In .NET Framework ASP.NET MVC/Web API, use the framework's IDependencyResolver with a scope per request.

5. Measuring progress and preventing backsliding

  • Count locator calls in CI (grep -c or a Roslyn analyser) and publish it on the team dashboard.
  • An architecture test (NetArchTest/ArchUnitNET) or a banned-API analyser (Microsoft.CodeAnalysis.BannedApiAnalyzers with BannedSymbols.txt) fails the build on new usages outside allowed folders.

Try it yourself

  1. Take a class that uses DateTime.Now and ConfigurationManager.AppSettings; write a characterisation test, then inject TimeProvider and options.
  2. Implement a bridge where a static locator delegates to a ServiceProvider; confirm old and new code get the same singleton.
  3. Add BannedApiAnalyzers with ServiceLocator.Get banned and see the build fail on a new call.
  4. Plot locator usage per week from git history to see a realistic migration curve.

💻 Code

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

⚠ Common mistakes

  • Mistake: Planning a big-bang "introduce DI" rewrite on a long-lived branch. Why it is wrong: it drifts from main, never merges and delays features. Instead: bridge the locator and convert incrementally with normal work.
  • Mistake: Letting the bridged locator resolve scoped services from the root provider. Why it is wrong: a scoped service resolved outside a scope lives as long as the root, so it behaves as a singleton: a 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.
  • Mistake: Turning static mutable state into a singleton without making it thread-safe. Why it is wrong: the race conditions remain, now behind an interface. Instead: use concurrent collections or IMemoryCache.
  • Mistake: Converting every static, including pure functions. Why it is wrong: it adds noise without creating useful seams. Instead: convert statics with side effects (time, I/O, config, state).
  • Mistake: Replacing 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).
  • Mistake: Refactoring without tests. Why it is wrong: legacy behaviour is implicit and easy to break. Instead: write characterisation tests first.
  • Mistake: Not stopping new locator usage, or not noticing resolution failures. Why it is wrong: the count never reaches zero, and a missing registration behind the locator only fails at run time. Instead: [Obsolete] and banned-API analysers, a composition-root test with ValidateOnBuild, and log the locator's InvalidOperationExceptions with the requested type during the migration.
  • Mistake: Changing lifetimes as a side effect of the migration without noticing. Why it is wrong: behaviour like per-process caching changes silently. Instead: map each static to an explicit lifetime and note it in the PR.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the composition root or IoC Why: Checks the fundamentals behind the migration
    How to answer

    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.

  2. When: Candidate talks about converting hand-rolled singletons Why: Checks thread-safe singletons and why DI registration replaces them
    How to answer

    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.
    • Double-checked locking: it's only correct with a 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.

  3. When: Candidate mentions adding tests as they refactor Why: Checks testing approaches enabled by DI
    How to answer

    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.

🛠 Real-world problems: how you handle them

Introducing DI into a legacy billing system without a freeze
Situation
At [company] a [10-year-old ASP.NET MVC / .NET Framework] billing system had [~600] calls to a static ServiceLocator, [~80] static helpers and almost no unit tests. The business needed [new invoicing rules] delivered over the next [two quarters] and would not approve a refactoring freeze.
Signals
Every billing change took [days] of manual regression testing; bugs from shared static state appeared under load (wrong exchange rates on concurrent requests); new developers took [weeks] to make safe changes.
Investigation
Mapped locator and static usage with a Roslyn-based count and grouped by module; identified billing as the most-changed area from git history. Found that ExchangeRateHelper used a static Dictionary written by multiple threads. Ran the app with ValidateScopes after introducing the container to find scoped services resolved from the root.
Resolution
Wrote characterisation tests around billing. Introduced a composition root and bridged ServiceLocator to the container, resolving scoped services from the request scope. Replaced the static exchange rate dictionary with a thread-safe singleton cache. Converted classes to constructor injection as features touched them, with TimeProvider and options replacing DateTime.Now and ConfigHelper.
Prevention
ADR describing the rules; ServiceLocator marked [Obsolete] and banned outside legacy folders with BannedApiAnalyzers; locator count published per build on the team dashboard; composition-root test with ValidateOnBuild and ValidateScopes in CI.

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.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me