Swinject / SwinjectStoryboard

Swinject extension for automatic dependency injection via Storyboard
MIT License
268 stars 141 forks source link

Cannot get reference to UIViewController registered for storyboard injection #5

Closed jlyonsmith closed 8 years ago

jlyonsmith commented 8 years ago

I'm using Swinject 1.1.1. I really want to be able to inject a reference to my UIViewController which has been registered for storyboard injection. I currently have a SpriteKit app where class GameViewController: UIViewController is injected into Main.storyboard via registerForStoryboard(). Creating this view controller causes creation of a bunch of SKScene's one of which needs a reference to the original GameViewController in order to be able to call presentViewController to show settings. I tried to resolve the GameViewController in the initComplete (to avoid a circular reference) but it comes back as nil. Am I missing something? Can this be made to work and if not, what's the underlying issue?

yoichitgy commented 8 years ago

I guess you need to call instantiateViewControllerWithIdentifier or instantiateInitialViewController to get dependencies injected via the storyboard. I should update the document to describe the usage explicitly.

If you show me essence of your code, I might be able to give more accurate answer. (I think you already know SwinjectStoryboard in this repo is for Swinject v2. V1.x includes SwinjectStoryboad by itself. )

jlyonsmith commented 8 years ago

OK, I finally got some time to dig into this. It appears the problem is my lack of understanding of what is actually going on with storyboard injection. It appears from SwinjectStoryboard.swift:90 that the UIVIewController is never actually saved in the container. The only place that you can get the controller is in the initComplete call. Is that correct?

yoichitgy commented 8 years ago

Yes, UIViewControllers are not stored in a container but just created and returned by calling factory closures, unless .Container scope is specified.

The place you can access the view controllers is, as you told, initCompleted which is the closure specified with registerForStoryboard method in the storyboard injection.

jlyonsmith commented 8 years ago

That makes sense as you would generally want to avoid an unnecessary strong reference to the UIVIewController by holding on to it in the Container. Thanks!