I was showing the team how to use Swinject the other day and one of them asked a question - Why do we use SwinjectStoryboard when it's just as easy to resolve dependencies during viewDidLoad() processing.
So for arguments sake I have this:
let diContainer = Container()
class ApplicationDelegate:UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
HomeViewController.register()
}
class HomeViewController:UIViewController {
var aDep:SomeClass!
static func register() {
diContainer.storyboardInitCompleted(HomeViewController.self) { resolver, controller in
controller.aDep = resolver.resolve(SomeClass.self)!
}
}
He was asking if this would work just as well:
class HomeViewController:UIViewController {
var aDep:SomeClass!
override func viewDidLoad() {
super.viewDidLoad()
self.aDep = diContainer.resolve(SomeClass.self)!
}
}
So my question is - is there a reason to SwinjectStoryboard rather than using resolve in viewDidLoad or is it just a matter of personal preference?
Resolving dependencies in viewDidLoad requires you to have access to the container. This means your view controllers are less flexible, since they'll all depend on the container (which is usually implemented as a singleton, as in your example).
Using SwinjectStoryboard allows you to decouple the view controllers form the container, making them only dependent on their actual dependencies.
It's just preference. Some people prefer using SwinjectStoryboard with storyboards with segues.
Off topic but the pattern you implemented was service locator pattern (not DI) as @mpdifran mentioned馃槈
Apple's UIViewController is designed for multiple responsibilities, and a lot of attempts in the recent few years are to address this problem by introducing new patterns other than MVC.
While handling dependency resolution in viewDidLoad, you are giving UIViewController another responsibility, which is generally not preferred.
Most helpful comment
Resolving dependencies in
viewDidLoadrequires you to have access to the container. This means your view controllers are less flexible, since they'll all depend on the container (which is usually implemented as a singleton, as in your example).Using
SwinjectStoryboardallows you to decouple the view controllers form the container, making them only dependent on their actual dependencies.