From the course: Swift: Writing Testable Code

Unlock this course with a free trial

Join today to access over 22,400 courses taught by industry experts.

What is a DI container?

What is a DI container?

- [Instructor] Since our classes now have complicated initializers, we're going to need a way to make them easier to instantiate. A Dependency Injection Container, or a DI container for short, can help us do this. The container will keep a map of each class type to an instance of that class. We can then instantiate any class by simply providing the type to the container. The container then automatically provides dependencies for the class. Let's take a look at a quick example to get an idea of how this works. So on the right we have a diagram representing our DI container. We would ask it for a URLSession class, and then it would instantiate a URLSession and provide the class back. We can then register several of these classes. And then when we ask for a PhotoDownloader class, it can then create a URLSession and a URLCache class, and then create the PhotoDownloader class for us and return the class to us. This allows us to create the PhotoDownloader class, rather than having to…

Contents