8 of 22 · System architecture
Dependency Injection
Dependency injection means an object receives what it depends on, usually through its initializer, instead of creating or looking it up itself. Concrete types are chosen in one place: the composition root.
How it's wired
- An object receives what it needs from outside.
- Init injection makes it impossible to build the object without them.
| Part | Owns | Looks like |
|---|---|---|
| Composition root | Create and wire concrete objects | AppContainer, App init |
| Consumer | Declare needs in init, never reach out | init(store: any NoteStoring) |
| Protocol | The seam tests and features swap | protocol NoteStoring |
| Implementation | Real or fake behavior | ThanksVault, InMemoryStore |
Swift example: static vs runtime DI
The same ComposerModel, wired four ways. The first two are checked at compile time; the last two resolve at runtime.
Static: initializer injection at a composition root
No library. The compiler proves every dependency exists. This is what SwiftPumpkin's AppContainer does.
@MainActor
final class ComposerModel {
private let notes: any NoteStoring
init(notes: any NoteStoring) { self.notes = notes }
}
// Composition root: the only place concrete types appear.
let notes = ThanksVault.onDisk()
let composer = ComposerModel(notes: notes)
// Test: pass a fake. No container, no global state.
let testComposer = ComposerModel(notes: ThanksVault.inMemory())Static, generated: Needle
Components declare what they need; a code generator checks at build time that an ancestor provides it. Scales to very large dependency trees without hand-threading initializers.
import NeedleFoundation
protocol ComposerDependency: Dependency {
var notes: any NoteStoring { get }
}
final class ComposerComponent: Component<ComposerDependency> {
var model: ComposerModel { ComposerModel(notes: dependency.notes) }
}
final class RootComponent: BootstrapComponent {
var notes: any NoteStoring { shared { ThanksVault.onDisk() } }
var composer: ComposerComponent { ComposerComponent(parent: self) }
}
// If no ancestor provides `notes`, the generator fails the build.Runtime: container with Swinject
Register factories, resolve on demand. Flexible and familiar from other platforms, but dependencies are hidden and a missing registration only shows up at runtime.
import Swinject
let container = Container()
container.register((any NoteStoring).self) { _ in ThanksVault.onDisk() }
.inObjectScope(.container) // one shared instance
container.register(ComposerModel.self) { resolver in
ComposerModel(notes: resolver.resolve((any NoteStoring).self)!)
}
let composer = container.resolve(ComposerModel.self)! // crashes if not registeredRuntime, keyed: swift-dependencies
Dependencies are looked up by key with a live default, and overridden per test or per scope with task-local values. Great ergonomics; the trade is that what a type depends on isn't in its initializer.
import Dependencies
// NoteStoring is Sendable (see the Contracts above), as DependencyKey requires.
private enum NotesKey: DependencyKey {
static let liveValue: any NoteStoring = ThanksVault.onDisk()
static let testValue: any NoteStoring = ThanksVault.inMemory()
}
extension DependencyValues {
var notes: any NoteStoring {
get { self[NotesKey.self] }
set { self[NotesKey.self] = newValue }
}
}
@MainActor
final class ComposerModel {
@Dependency(\.notes) var notes
}
// Test override, scoped to this operation only:
let model = withDependencies { $0.notes = ThanksVault.inMemory() } operation: {
ComposerModel()
}Library snippets show the shape of each API; check the current docs for exact signatures before copying.
What matters at scale
- Constructor injection makes dependencies impossible to forget. A long initializer is a signal the type does too much, not a reason to fall back to globals.
- A service locator (container.resolve) hides dependencies again and moves failures from compile time to runtime. Use a container only at the root, if at all.
- Scope matters more than mechanism: app-wide (network client), user session (caches, user store, dropped on logout), screen. Scopes are how you stop one account's data leaking into the next.
- Default arguments give zero-ceremony injection: init(store: any NoteStoring = ThanksVault.onDisk()) keeps call sites clean while tests pass fakes.
- Static (compile-time) DI resolves the graph when you build: plain initializer injection at a composition root, or a code-generated graph like Needle. A missing dependency is a build error. Runtime DI resolves when the app runs: a container like Swinject, or swift-dependencies. Less plumbing and easy overrides, but a missing registration is a crash or a silent default.
How I set it up
| Everything with side effects | Inject it: storage, network, clock, analytics. |
|---|---|
| App launch | One composition root builds the graph. |
| Login and logout | A session scope you can drop as a whole. |
Compared
Ways to inject
| Initializer | Property | Locator | Environment | |
|---|---|---|---|---|
| Compile-time safe | Yes | Partly | No | Partly |
| Dependencies visible | In signature | As properties | Hidden | Per view |
| Use for | Almost everything | Storyboard VCs | Avoid | Shared models |
Static vs runtime DI
| Static | Runtime | |
|---|---|---|
| Missing dependency | Build error | Crash or silent default |
| Dependencies visible | In initializers / components | Inside the container or key |
| Plumbing | More (or generated) | Less |
| Test overrides | Pass fakes to init | Re-register or override keys |
| Fits | Large apps wanting safety at scale | Fast iteration, SwiftUI-heavy code |
Expert notes
- The goal is a dependency graph you can see and scope. DI is just how you get there.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Dependency Injection in 30 seconds.
- Dependency injection means an object receives what it needs, usually through its initializer, instead of creating or looking it up.
- Concrete types are chosen in one composition root, so tests pass fakes and features swap implementations.
- I prefer static injection, where a missing dependency is a build error, over runtime containers that fail while the app runs.
- The real design work is scoping: app, user session and screen.
Initializer, property and parameter injection in Swift: when do you choose each?
- Default to initializer injection, like
init(store: any NoteStoring), so an object is complete the moment it exists. - Use property injection only for system-created classes, like storyboard view controllers, and accept the property may be unset or changed later.
- Use parameter injection for legacy code, static APIs, or a dependency that only one call needs.
A teammate proposes a global service locator so any class can fetch its dependencies. What's your concern?
- A locator hides dependencies.
- Every class depends on the locator itself, and its real needs are scattered across lookup calls instead of visible in
init. - A missing registration only shows up at runtime.
- It's acceptable for app code you fully control.
- For shared components other teams reuse, prefer injection.
- Separating configuration from use matters more than which one you pick.
A view controller loaded from a storyboard needs an API client, but you don't control its initializer. How do you inject it?
- Use property injection, like
var apiClient: APIClient = .live, set right after instantiating from the storyboard. - It's the standard workaround for system-created classes.
- The gotcha is that a mutable property can be left unset or swapped unexpectedly.
- On iOS 13 and later,
instantiateViewController(identifier:creator:)lets you use a real initializer, so prefer that where you can.