Dependency injection with Storyboard

Alexandros Baramilis
2 min readApr 24, 2019

--

If you’ve never heard about dependency injection, it’s basically when you give an object its dependencies, usually at the point of initialisation, instead of letting the object create them, or instead of using a singleton.

Dependency injection has multiple benefits, with the best one probably being that it makes testing much easier, because you can create mock dependencies and pass them to your objects.

Another benefit is that it makes the responsibilities of each class clearer and you can easily tell what each object needs by looking at the top of the class where you declare the dependencies. It also helps you to decouple your project’s logic. For example, your class can have a dependency that implements some functionality conforming to a certain protocol and you wouldn’t care about how this functionality is implemented. The implementation can change but as long as the interface stays the same, your class doesn’t have to change anything.

You can read a bit more about dependency injection here.

The problem with using Storyboard is that you don’t have access to the point of a view controller’s instantiation. So you can’t use the initialiser injection pattern mentioned in the above article. But you can go for property injection from the AppDelegate.

I will give an example from my Breather Series Part 2.

In the MainViewController class, we have a viewModel dependency which is of type MainViewModel. This is a class in this project, but it could also be a struct or a protocol. In any case, you can pass it any class that is a subclass of MainViewModel, or in the protocol scenario, any protocol conforming to the MainViewModel protocol.

The viewModel dependency

To access the MainViewController and inject it we can use the AppDelegate’s applicationDidFinishLaunching method, access the root controller which in this case happens to be a navigation controller and get the top view controller which is the MainViewController. Then, we instantiate a MainViewModel object and inject it in the MainViewController.

Dependency injection when using Storyboard

You can find another good article about dependency injection with Storyboard here.

--

--