DEV Community

Discussion on: Dependency Injection in SwiftUI

Collapse
 
darren120 profile image
Darren Zou

Does this mean frameworks like Swinject is obsolete since environment object passes the class down? Also multiple environment object is ok too?

Collapse
 
mokagio profile image
Gio Lodi

Hey Darren Zou 👋 Thank you for stopping by and leaving a comment.

I wouldn't say advanced DI frameworks like Swinject are obsolete, no. Swinject does much more than the basic injection I talked about in the post; it resolves dependencies at runtime, too.

The code sample from the repo explains it quite well:

let container = Container()
container.register(Animal.self) { _ in Cat(name: "Mimi") }
container.register(Person.self) { r in
    PetOwner(pet: r.resolve(Animal.self)!)
}
Enter fullscreen mode Exit fullscreen mode

Not only you can access any dependency registered in the container without having to explicitly pass that dependency along the hierarchy tree (which is useful when you have many dependencies to keep things tidy) but you can resolve the concrete implementation for a registered protocol at runtime. That's pretty cool.


Regarding the multiple environment object question. If by that you mean multiple calls to .environmentObject(_:) with instances of different types, than yes, that will work too. It's not limited to only one injectable object.

E.g.:

NavigationView {
  ToReadList().navigationTitle("To Read 📖")
}
.environmentObject(readingListController)
.environmentObject(userPreferencesController)
Enter fullscreen mode Exit fullscreen mode

One thing to keep in mind, though, is that the objects you register with .environmentObject(_:) need to conform to @ObservableObject.