Dependency injector for MVVM architectures in swift
Little tool useful to avoid boilerplate code while passing down your different services between view models.
If you like to use plain Dependency Injection, meaning passing your dependencies in the initialiser, but you often end up with very fat initialiser, then this is for you.
In this example, we see the initialiser stacking up services. And this goes even worse if that view model creates other view model that needs different services!
class ViewModel {
let apiService: ApiService
let imageService: ApiService
let fileService: FileService
init(apiService: ApiService, imageService: ApiService, fileService: FileService) {
self.apiService = apiService
self.imageService = imageService
self.fileService = fileService
}
}
We reduce the initialisation to only 1 parameter, which will always be the same between view models.
class ViewModel {
let injector: Injector
let apiService: ApiService
let imageService: ApiService
let fileService: FileService
init(injector: Injector) {
self.injector = injector
self.apiService = injector.dependency()
self.imageService = injector.dependency()
self.fileService = injector.dependency()
}
}
If you are fine with having your dependencies as variables, then it gets really straightforward:
class ViewModel {
let injector: Injector
lazy var apiService: ApiService = injector.dependency()
lazy var imageService: ApiService = injector.dependency()
lazy var fileService: FileService = injector.dependency()
init(injector: Injector) {
self.injector = injector
}
}
This doesn't do magic, you will likely pass down all your dependencies to all your view models. It is only a nice piece of code to remove some boilerplate, keep in mind release count management.