SwiftPumpkin

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

CreatesInjects via initUsesConformsComposition rootBuilds the graphImplementationConcrete typeConsumerUses an abstractionProtocolThe contract
calls or tellsreports backOnly the composition root knows concrete types. Everything else receives what it needs.
  • An object receives what it needs from outside.
  • Init injection makes it impossible to build the object without them.
PartOwnsLooks like
Composition rootCreate and wire concrete objectsAppContainer, App init
ConsumerDeclare needs in init, never reach outinit(store: any NoteStoring)
ProtocolThe seam tests and features swapprotocol NoteStoring
ImplementationReal or fake behaviorThanksVault, 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 registered

Runtime, 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 effectsInject it: storage, network, clock, analytics.
App launchOne composition root builds the graph.
Login and logoutA session scope you can drop as a whole.

Compared

Ways to inject

InitializerPropertyLocatorEnvironment
Compile-time safeYesPartlyNoPartly
Dependencies visibleIn signatureAs propertiesHiddenPer view
Use forAlmost everythingStoryboard VCsAvoidShared models

Static vs runtime DI

StaticRuntime
Missing dependencyBuild errorCrash or silent default
Dependencies visibleIn initializers / componentsInside the container or key
PlumbingMore (or generated)Less
Test overridesPass fakes to initRe-register or override keys
FitsLarge apps wanting safety at scaleFast 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.

30-second answer

Explain Dependency Injection in 30 seconds.

SwiftAsked directly

Initializer, property and parameter injection in Swift: when do you choose each?

System designAsked indirectly

A teammate proposes a global service locator so any class can fetch its dependencies. What's your concern?

iOS codingAsked indirectly

A view controller loaded from a storyboard needs an API client, but you don't control its initializer. How do you inject it?

Read it in the app's source