Dependency Injection feel like a very complicated topic but in fact it is very simple. We as devs all try to follow design principle like SOLID so that our code is properly structured in a modular way and not a spaghetti code. Dependency injection really help with this. It also helps in mocking/testing our code.
Dependency injection literally means injecting the dependency. In programming world it means injecting the dependencies our code needs in order to work. There are three flavors of dependency injection in Swift
- Initializer Based
- Parameter Based
- Property Based
In this blog we will focus on Initializer Based Dependency Injection. Lets take a look at this example
class FileUploader {
var fileManager:FileManager
var networkManager:NetworkManager
init() {
self.fileManager = FileManager()
self.networkManager = NetworkManager()
}
}
If you look at the example above, FileUploader instance initialization is dependent on file manager and network manager. So this is a very tightly coupled code. We can use initializer based Swift Dependency Injection to make this a little better
class FileUploader {
var fileManager:FileManager
var networkManager:NetworkManager
init(fileManager:FileManager,
networkManager:NetworkManager) {
self.fileManager = fileManager
self.networkManager = networkManager
}
}
So this subtle change makes a huge difference, instead of hardcoding file manager and network manager in the init method of FileUploader we are passing the required/dependency as parameters externally. This is basically what dependency injection is. We will talk about other flavors of dependency injection in coming articles.