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
- Layers: Domain, Data and Presentation
- Use Case and Repository Patterns
- Dependency Inversion with Protocol Abstractions
- Wiring Layers Together without a DI Framework