Dependency Injection Container in Swift
source link: https://medium.com/@ronen.harati/dependency-injection-container-in-swift-b4d7e139338c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to loosely couple your whole project
Feb 4 ·4min read
Photo by Patrick Brinksma on Unsplash
In this article I will talk about Dependency Injection Containers or DICs’ in swift. Im my previous article I talked about 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 classes from its’ dependencies, by injecting its dependencies from the outside world.
Using DI helps decoupling a class, but does not fully solve the problem. What about the parent class who creates the child class? We just move the coupling from the child class to the parent class. The parent class is now tightly coupled, lets 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
. Lets see how that would look like.
By injecting serviceOne
we have made ParentClass
loosely coupled! This is perfectly fine but lets 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, lets take a look at what it would look like.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK