Dependency injection
Follow the history of IoC, DIP, and DI to distinguish object use, assembly, and lifetime, then test the relationship with a small sender example.
· Last updated: 2026-11-07 · 9 min read
Overview
Dependency injection (DI) wires objects or functions from the outside instead of letting them build their own collaborators. Notification logic simply calls a sender, while the outer assembly code decides whether that sender talks to an email gateway or an SMS service, so you can swap delivery channels without touching a line of notification code.
Any helper another piece of code needs, a database client, a clock, a file store, is a dependency. Injection names the direction of wiring: rather than calling new inside the consumer, outer assembly code hands the collaborator in, often through nothing fancier than a constructor parameter or function argument.
Why split the two? Because business rules and wiring change for different reasons: tweaking a discount formula alters domain logic, whereas pointing that formula at an in-memory test store alters only configuration, and tangling them together forces you to spin up a live database just to run a unit test or edit domain code just to switch transport layers.
Every DI design ultimately answers three questions: which collaborator runs, which outer layer wires it, and how long that wired instance stays alive.
History
1988: Ralph Johnson and Brian Foote described a reusable framework calling application-specific behavior as inversion of control (IoC) in “Designing Reusable Classes”.1
May 1996: Robert C. Martin presented the dependency inversion principle (DIP), concerning source dependency direction, in “The Dependency Inversion Principle” in C++ Report.2
January 23, 2004: Martin Fowler coined the term Dependency Injection in “Inversion of Control Containers and the Dependency Injection pattern” to describe how lightweight containers such as PicoContainer and Spring wire objects, contrasting it with Service Locator.3
The 1988 framework paper asks who initiates calls, the 1996 DIP article asks which way source-code arrows point, and the 2004 DI essay asks how objects get wired together. They overlap, but they are not the same question.
Inversion of control and frameworks
When Ralph E. Johnson and Brian Foote studied reusable frameworks in 1988, they focused on who holds the steering wheel. Ordinarily, application code calls a library function whenever it needs one; in a framework, the reusable skeleton calls into application-supplied hooks instead, an inverted call direction Johnson and Foote named inversion of control (IoC) while asking which parts of a framework should vary through subclasses and which should be plugged in as separate objects.1
In that broad sense, even an event loop firing callbacks is IoC. Passing pre-built collaborators into an object is one specific wiring problem inside a much larger family.
Dependency direction and DIP
Robert C. Martin's dependency inversion principle (DIP), published in May 1996, shifts attention from runtime call order to compile-time source dependencies: both high-level policy and low-level detail should depend on abstractions so that swapping a storage engine or device driver does not force edits to business policy.2
DI and DIP therefore pull on different axes. Handing a concrete SmtpEmailSender into a constructor is genuine dependency injection because the object arrived from outside, even though the consumer still depends directly on a concrete class.
Injection styles and Service Locator
Martin Fowler's January 23, 2004 essay tackled object wiring across component boundaries directly. Because saying “inversion of control” left readers asking which control was inverted, Fowler coined Dependency Injection to name the pattern where an external assembler supplies a component's dependencies.3
He grouped the mechanics into three styles: constructor injection passes collaborators at birth, setter injection attaches them afterward, and interface injection defines an explicit interface for pushing dependencies in. What matters is not a particular container's XML or annotations, but where assembly stops and execution begins.
Fowler also set DI beside Service Locator. A locator lets the consumer reach into a registry and pull out what it needs; DI pushes collaborators in as arguments.3 Both decouple the consumer from a fixed implementation, yet DI advertises every required collaborator right in the constructor signature, whereas a locator hides those lookups inside the method body, and Fowler's split between assembly and use works just as cleanly in ten lines of manual wiring as it does inside a framework container.
DI today: lifetimes and assembly
Because modern containers create and cache the objects they wire, DI quickly becomes a conversation about object lifetimes. In .NET's built-in container, transient spins up a fresh instance on every resolution, scoped shares one instance across a unit of work such as a single web request, and singleton keeps one instance alive for the lifetime of the container.4
Spring draws a similar line between a container-scoped singleton and a prototype that yields a new object every time it is requested. Watch the boundary between them: if a singleton takes a prototype in its constructor, that dependency is resolved once when the singleton is born, so the singleton hangs on to that single instance forever unless you arrange a lookup boundary.5
Lifetimes turn wiring into a state-safety question. Inject a request-scoped state holder into a long-lived singleton, or forget who owns closing a socket or file handle, and a clean dependency graph still fails at runtime.
Polymorphism lets caller code talk to different implementations through one interface, while DI moves the choice of which implementation to plug in out to the assembly layer. No interface is even required. Handing in a single concrete class or a plain function argument is already DI, long before you ever install a container.
Example: separating assembly from use
The code below splits the notification logic from the outer wiring that picks a delivery channel.
type Sender = { send(message: string): string };
function createNotifier(sender: Sender) {
return {
notify(name: string) {
return sender.send(`Hello, ${name}`);
},
};
}
const mail: Sender = { send: message => `mail:${message}` };
const sms: Sender = { send: message => `sms:${message}` };
console.log(createNotifier(mail).notify('Ada'));
console.log(createNotifier(sms).notify('Ada'));
Running it prints mail:Hello, Ada and sms:Hello, Ada. Outer assembly picks mail or sms, hands it to createNotifier, and calls notify('Ada'), which calls sender.send: the exact same notification code driven by two different transports.
Scoped instance sharing and captive-dependency validation
The C# example below uses Microsoft.Extensions.DependencyInjection to verify how scoped and singleton registrations share instances across scopes, and how validateScopes: true blocks a captive dependency when a singleton attempts to hold a scoped service.
using System;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddScoped<RequestContext>();
services.AddSingleton<CaptiveHolder>();
using var provider = services.BuildServiceProvider(validateScopes: true);
using var scopeA = provider.CreateScope();
using var scopeB = provider.CreateScope();
var first = scopeA.ServiceProvider.GetRequiredService<RequestContext>();
var again = scopeA.ServiceProvider.GetRequiredService<RequestContext>();
var other = scopeB.ServiceProvider.GetRequiredService<RequestContext>();
Console.WriteLine(ReferenceEquals(first, again));
Console.WriteLine(!ReferenceEquals(first, other));
try
{
scopeA.ServiceProvider.GetRequiredService<CaptiveHolder>();
}
catch (InvalidOperationException)
{
Console.WriteLine("captive-dependency-blocked");
}
sealed class RequestContext { }
sealed record CaptiveHolder(RequestContext Context);True
True
captive-dependency-blockedResolving RequestContext twice inside scopeA returns the exact same instance (True), while resolving it from scopeB yields a separate instance (True). Because CaptiveHolder is registered as a singleton, injecting the scoped RequestContext into its constructor with scope validation disabled would resolve and retain that context in the root scope for the lifetime of the container; enabling validateScopes: true makes the provider reject that resolution with an InvalidOperationException (captive-dependency-blocked).
See also
Footnotes
- Ralph E. Johnson and Brian Foote, “Designing Reusable Classes,” JOOP 1(2), 1988, pp.22–35, “White-box vs Black-box Frameworks.” Authors' copy. ↩
- Robert C. Martin, “The Dependency Inversion Principle,” C++ Report, May 1996 (Engineering Notebook column). Author's paper. ↩
- Martin Fowler, “Inversion of Control Containers and the Dependency Injection pattern,” 2004-01-23. Article. ↩
- Microsoft, “Service lifetimes.” Official documentation. ↩
- Spring Framework, “Bean Scopes.” Official documentation. ↩