-
Notifications
You must be signed in to change notification settings - Fork 7
Dependency injection
Let's assume everyone knows what is dependency injection and why it's good to use this pattern. If not, read about it at least on Wikipedia before you continue 😉
Back in time we were using Swinject for DI but after some experience we decided to stop using it. It was too complicated for new guys (and often even for experienced ones) in the team and it was just overkill for our needs.
That's why we were inspired by article from Krzysztof Zabłocki about using protocol composition for DI. We definitely recommend reading it to understand it well, but let's look at brief example.
All services, managers and factories have defined a protocol Has{ServiceName}
or Has{FactoryName}
as shown in example below.
protocol HasExampleAPI {
var exampleAPI: ExampleAPIServicing { get }
}
protocol HasExampleViewModelFactory {
var exampleVMFactory: () -> ExampleViewModeling { get }
}
When you need to use ExampleAPIService
as a dependency in your VM, you do it like this
final class ExampleViewModel: BaseViewModel, ExampleViewModeling, ExampleViewModelingActions {
typealias Dependencies = HasExampleAPI
let exampleAPI: ExampleAPIServicing
init(dependencies: Dependencies) {
exampleAPI = dependencies.exampleAPI
super.init()
}
}
Continue to Models ➡️