iOS Composition Root: A key concept for achieving loose coupling | iOS Lead Essentials Podcast #015

When applying Dependency Injection (DI) principles in your iOS codebases, you rightly end up pushing and deferring the instantiation of dependencies up the chain.

For example, instead of coupling a ViewModel with a concrete Service by instantiating it directly:

struct BooksViewModel {
  let service = BooksAPIService() ❌
}

Your ViewModels will depend on abstractions (e.g., protocol or closure) passed via initializer injection:

protocol BooksService { ... }

struct BooksViewModel {
  let service: BooksService ✅
}

This way, you can easily develop, maintain, and test your implementations in isolation. You also gain the ability to inject different kinds of services, making your codebase more composable and Open/Closed.

A common question now is...

"Where should I instantiate and inject the Service and any other dependencies?!"

In the Composition Root!

And in this podcast episode, you’ll find answers to frequently asked questions about the Composition Root and how you can leverage it on your iOS apps, including:

  • What’s a Composition Root?
  • Why do I need a Composition Root in my iOS apps?
  • Where should I create objects to achieve a clean and modular design?
  • Do I need a Composition Root if I use a DI container?
  • Should I use Dependency Injection for a global static struct used for Styling the app with colors/fonts/icons?
  • Is the Main Storyboard the Composition Root of my iOS app?
  • Can I use storyboards for instantiating my View Controllers or should I use only code from the Composition Root?
  • Can you give an example of a simple app with a Composition Root?
  • Wouldn’t the Composition Root negatively impact memory usage and performance if all components were instantiated upfront?
  • How can I test the Composition Root?
  • Do I need the Composition Root for simple apps with a couple screens?
  • Is the Composition a single component, or how many classes or structs make up the Composition Root?

This episode is full of insights you can apply in your current projects to help you and your team achieve loose coupling in the codebase, drastically improve your productivity, and deliver much more value to your company and customers.

Subscribe now to our Youtube channel and Podcast to catch new episodes.

Notes