Skip to main content

Why Dependency Injection in .NET Modernization Is an Architecture Decision, Not a Testing Tool

Dependency injection (DI) is usually sold as a way to make unit tests easier. In a legacy .NET modernization that is the smallest part of its value. The larger value is that DI forces a team to name the contracts between components that were tangled together for years, and once those contracts exist you can replace what sits behind them one piece at a time.

This article is organized as the questions that come up when you start, in the order they usually appear.

What problem does DI actually surface?

Older .NET code often mixes construction, configuration and execution in one method. A routine that sends an email might create an SMTP client, read a connection string from a config file, build the message, log the attempt, retry on failure and update a database row, all inline. You cannot test it without live dependencies, and you cannot change any one of those concerns without touching the others.

DI does not fix that code by itself. What it does is ask an uncomfortable question: what does this class really depend on? Trying to inject an email sender reveals that it needs configuration, logging, retry behavior and persistence. Those dependencies were always there. DI makes them explicit and therefore replaceable.

Which interface should you extract first?

The first extraction sets the pattern for the rest of the migration, so choose one with a clear edge. Calls to external services are a good starting point:

  • Clear failure boundary. External services fail independently of your logic, so hiding them behind an interface makes failure handling explicit.
  • Easy to fake. A hand-written fake that returns canned responses is often faster and more reliable than configuring a mocking framework for every case.
  • Versionable contract. External systems change. An interface gives you one place to absorb that change while callers migrate gradually.

Persistence is usually a worse first choice when several services share the same schema and stored procedures. A repository interface would freeze a data access pattern you probably need to change.

A typical use of this approach is replacing WCF clients with REST calls. Define something like ICustomerDataService, keep the WCF implementation, add an HTTP implementation, and choose between them with a feature flag. Callers never learn which transport is in use.

How do you introduce DI without a big-bang rewrite?

Legacy applications often have no composition root: objects are created inline and configuration comes from static classes. Adding a container normally means changing how the application starts, which is risky to do all at once.

A safer route is to introduce DI at the seam between old and new code. The legacy path keeps creating its dependencies by hand. New components use constructor injection, and a small adapter connects the two.

public class ModernOrderProcessor
{
    private readonly IEmailSender _emailSender;
    private readonly ICustomerService _customerService;

    public ModernOrderProcessor(IEmailSender emailSender, ICustomerService customerService)
    {
        _emailSender = emailSender;
        _customerService = customerService;
    }

    public void ProcessOrder(int orderId)
    {
        // new logic using injected dependencies
    }
}

public class OrderProcessorAdapter
{
    private readonly IServiceProvider _services;

    public OrderProcessorAdapter(IServiceProvider services) => _services = services;

    public void ProcessOrder(int orderId, bool useModernPath)
    {
        if (useModernPath)
            _services.GetRequiredService<ModernOrderProcessor>().ProcessOrder(orderId);
        else
            new LegacyOrderProcessor().ProcessOrder(orderId);
    }
}

The adapter is not pretty, and it is meant to be temporary. Once the new path is proven, the flag and the legacy branch are deleted and the adapter disappears with them.

What does DI unlock besides testing?

  • Swapping implementations. Transport, storage and other infrastructure can change behind an interface without touching callers.
  • Moving configuration out of XML. Wrap the old ConfigurationManager behind an interface of your own, then replace it with a provider that reads environment variables or a secrets service, one service at a time. Where you can, prefer the standard IConfiguration over inventing a competing interface.
  • Adding observability. If logging goes through an abstraction, you can decorate it with correlation IDs and timing without editing business code. Use Microsoft.Extensions.Logging's ILogger<T>, or name your own interface something different (for example IAppLogger) so it does not collide with the framework type.

When does DI become a liability?

With inline construction the compiler catches a missing dependency. With a container, a misconfigured registration or a wrong lifetime fails at runtime. Three habits keep that risk down:

  1. Validate the container. Turn on ValidateOnBuild and ValidateScopes for the built-in provider, and keep an integration test that resolves every registered service.
  2. Keep graphs shallow. Depend on interfaces, not on services with deep trees of their own. Deep graphs make lifetimes hard to reason about and invite circular dependencies.
  3. Treat large constructors as a smell. If a class needs more than about five dependencies, it probably has too many responsibilities. Split it or group related dependencies behind one interface.

How do you choose lifetimes?

LifetimeGood forWatch out for
SingletonStateless, thread-safe services and shared infrastructureAny mutable state shared across requests
ScopedPer-request state such as user identity or correlation IDsA scope exists per HTTP request in ASP.NET Core; in a plain Lambda handler you must create one yourself
TransientLightweight services that must not share stateExpensive objects created on every resolution

A classic lifetime mistake involves HttpClient. Creating a new client for every call can exhaust sockets under load, but the usual fix is not a hand-rolled singleton. Register clients through IHttpClientFactory (or typed clients), which manages handler lifetime and avoids both socket exhaustion and stale DNS. If you do use a long-lived client, configure a connection lifetime on the underlying handler.

A short checklist

  1. Start with external dependencies: service clients, API wrappers, configuration providers.
  2. Define interfaces as contracts, without leaking schemas, headers or serialization formats.
  3. Introduce DI at the seam between old and new code instead of everywhere at once.
  4. Validate the container at startup and in an integration test.
  5. Keep dependency graphs shallow and constructors small.
  6. Pick lifetimes based on state and thread safety, and use IHttpClientFactory for HTTP.
  7. Use feature flags to route between old and new implementations during the migration.

Seen this way, DI is less a testing convenience and more the mechanism that turns a tangled monolith into replaceable parts. Testing improves as a side effect.

Comments