0Pricing
Swift Academy · Lesson

Wiring Layers Together without a DI Framework

Composing objects at the app entry point using a Composition Root pattern.

Composition Root

The Composition Root is the single location where all objects are instantiated and wired together. In a SwiftUI app, it's typically @main.

@main
struct MyApp: App {
  // All wiring happens here
  private let container = AppContainer()
  var body: some Scene {
    WindowGroup { container.makeRootView() }
  }
}

AppContainer Pattern

An AppContainer struct/class builds the object graph, hiding wiring complexity from the App struct.

final class AppContainer {
  let db = SQLiteDatabase()
  lazy var userRepo: UserRepository = RemoteUserRepository(db: db)
  lazy var fetchUser = FetchUserUseCase(repo: userRepo)
  lazy var profileVM = ProfileViewModel(useCase: fetchUser)
  func makeRootView() -> some View { ProfileView(viewModel: profileVM) }
}

All lessons in this course

  1. Layers: Domain, Data and Presentation
  2. Use Case and Repository Patterns
  3. Dependency Inversion with Protocol Abstractions
  4. Wiring Layers Together without a DI Framework
← Back to Swift Academy