Dependency Injection is a technique where one object supplies the dependency of another object.
Dependency Injection is used to write loosely coupled code. Using dependency injection in our code, we are giving an instance variable to an object.
The main objective of Dependency injection is that instead of creating the dependency internally an object can retrieve it from the outside.
Now, instead of giving our object the responsibility of creating its own dependency, we inject the dependencies to the object instead.
There are below types of Dependency injections
- Property Injection
- Constructor Injection
- Method Injection
Property Injection
Let’s understand with the help of code
1 2 3 |
class DemoViewModel { var demo = Demo() } |
In the above example we have a DemoViewModel which carries and instantiates the property and creating it’s own dependency.
Let’s take another example
1 2 3 4 5 6 7 |
class DemoViewModel { var demo = Demo? } let demoViewModel = DemoViewModel() let demo = Demo() demoViewModel.demo = demo |
Here, the view model object is not creating its own dependency. The dependency is injected into the view model via demo property and is receiving it from outside.
Constructor Injection
Another type of Dependency injection is constructor injection where the dependency is injected into an object right at its inception.
Let’s take the example of constructor injection.
1 2 3 4 5 6 |
class DemoViewModel { var demo = Demo init(demo: Demo) { self.demo = demo } } |
As we can see the entire view model can be initialize through one property, hence the dependency is located at constructor part.
We generally prefer constructor injection because it prevents us from using an object that is not fully configured.
Method Injection
As the name suggests in method injection dependencies are injected through methods.
Let’s take below example
1 2 3 |
protocol DemoManager { fun demoMethod(in demo: Demo) } |
Here we can see protocol has a method on its own that can takes in an injected dependency.
I hope you got brief idea about Dependency Injection in Swift.
Thanks for reading 🙂