Middle
What dependency injection methods do you know?.
sobes.tech AI
Answer from AI
- Initializer (Initializer Injection)
- Property/Setter (Property/Setter Injection)
- Method (Method Injection)
// Initializer (Initializer Injection)
class MyClass {
let dependency: Dependency
init(dependency: Dependency) {
self.dependency = dependency
}
}
// Property/Setter (Property/Setter Injection)
class MyClass {
var dependency: Dependency?
}
// Using setter
let instance = MyClass()
instance.dependency = concreteDependency
// Method (Method Injection)
class MyClass {
func performAction(with dependency: Dependency) {
//... use dependency ...
}
}
The initializer is the most common and recommended way, as it guarantees that the dependency is present when the object is created. Property is used when the dependency is optional or unknown at initialization. Method is used when the dependency is only needed for a specific method.