Using Dependency Injection to Mock Network API Service in View Controller
Dependency Injection is a software engineering technique that can be used to pass other object/service as a dependency to an object that will use the service. It’s sometime also called inversion of control
, which means the object delegates the responsibility of constructing the dependencies to another object. It’s the D part of the SOLID
design principles, dependency inversion principle.
Here are some of the advantages of using dependency injection in your code:
1. Better separation of concerns between construction and the use of the service.
2. Loose coupling between objects, as the client object only has reference to the services using Protocol/Interface that will be injected by the injector.
3. Substitutability, which means the service can be substituted easily with other concrete implementation. For example, using Mock object to return stub data in integration tests.
How to use Dependency Injection
There are 3 approaches that we can use for implementing dependency injection in our class:
- Using
Initializer
. With initializer, we declare all the parameter with the interface that will be injected into the class. We assign all the parameters to the…