Dependency Injection Types
suggest changeThis example will demonstrate how to use Dependency Injection (DI) design pattern in Swift using these methods:
- Initializer Injection (the proper term is Constructor Injection, but since Swift has initializers it’s called initializer injection)
- Property Injection
- Method Injection
Example Setup without DI
protocol Engine {
func startEngine()
func stopEngine()
}
class TrainEngine: Engine {
func startEngine() {
print("Engine started")
}
func stopEngine() {
print("Engine stopped")
}
}
protocol TrainCar {
var numberOfSeats: Int { get }
func attachCar(attach: Bool)
}
class RestaurantCar: TrainCar {
var numberOfSeats: Int {
get {
return 30
}
}
func attachCar(attach: Bool) {
print("Attach car")
}
}
class PassengerCar: TrainCar {
var numberOfSeats: Int {
get {
return 50
}
}
func attachCar(attach: Bool) {
print("Attach car")
}
}
class Train {
var engine: Engine?
var mainCar: TrainCar?
}
Initializer Dependency Injection
As the name says, all dependencies are injected through the class initializer. To inject dependencies through the initializer, we’ll add the initializer to the Train class.
Train class now looks like this:
class Train {
let engine: Engine?
var mainCar: TrainCar?
init(engine: Engine) {
self.engine = engine
}
}
When you create a Train, use the initializer to inject a specific Engine:
let train = Train(engine: TrainEngine())
NOTE: The main advantage of the initializer injection versus the property injection is that we can set the variable as private variable or even make it a constant with the let keyword (as we did in our example). This way we can make sure that no one can access it or change it.
Properties Dependency Injection
Property injection is even simpler than initializer injection. Inject a PassengerCar into the train already created:
train.mainCar = PassengerCar()
That’s it. Our train’s mainCar is now a PassengerCar instance.
Method Dependency Injection
Method injection is different: it does not store the dependency on the object. It only supplies a dependency for one method. If a dependency is used in a single method, the whole object usually should not depend on it. Add this method to Train:
func reparkCar(trainCar: TrainCar) {
trainCar.attachCar(attach: true)
engine?.startEngine()
engine?.stopEngine()
trainCar.attachCar(attach: false)
}
Calling the method injects the TrainCar for that call only:
train.reparkCar(trainCar: RestaurantCar())