Dependency Injection Containers in Swift

How to loosely couple your whole project

Photo by Patrick Brinksma on Unsplash

In this article, I will talk about Dependency Injection Containers or DICs’ in swift. In my previous article, I explored how to decouple code in Swift, and introduced four levels of the decoupling ladder, take a look if you are not sure what I mean. I have mentioned Dependency Injection or DI, as a method used to decouple a class from its dependencies, by injecting its dependencies from the outside world.

Using DI helps to decouple a class, but does not fully solve the problem. What about the parent class which creates the child class? We just move the coupling from the child class to the parent class. The parent class is now tightly coupled, let’s look at an example.

ParentClass creates both the serviceOne and serviceTwo . ServiceOne has a dependency to ServiceTwoProtocol and we can assume they are both loosely coupled or decoupled. ParentClass however is tightly coupled to ServiceOne and ServiceTwo , because it creates specific objects that can not be replaced. How then can we decouple ParentClass ?

One way is to inject ParentClass ’ dependencies, which in this case is serviceOne . Let’s see what that would look like.

By injecting serviceOne we have made ParentClass loosely coupled! This is perfectly fine but let’s think about this a bit deeper. We didn’t fully solve the issue, because now LooselyCoupledParentClass ’ parent will be tightly coupled. The class that creates the objects will always be tightly coupled to the created objects. We just passed on the problem to some other class. How then can we decouple as many classes as possible?

In a complex project, there may be many classes, each one with its own dependencies. These classes will probably be ordered into a complex hierarchy. The creation of the objects will probably be scattered around, causing many classes to be tightly coupled.

In order to avoid this, we can create one object which is responsible for creating all other objects. You may have guessed it, I’m referring to the dependency injection container object, let’s take a look at what it would look like.