使用Swinject在对象之间共享对象实例

时间:2017-12-12 18:15:39

标签: ios iphone swift dependency-injection swinject

我开始在我的应用中使用Swinject,我希望在presenters(Viper / MVP)或viewControllers(非Viper)之间共享rootNavigator的实例。我遇到的主要问题是我想在appRootNavigator中分享presenters,但是我放弃了window的实例,因为当我注册一个新模块swinject时会生成一个新的该类的实例(AppRootNavigator)。如何在AppRootNavigator之间共享presenters

在代码的这一部分中,我尝试更改navigator的{​​{1}},但它永远不会进入if。

presenter

我不知道另一种方法。

这是if let presenter = container.resolve(SignupPresenter.self, argument: self){ signUpController.presenter = presenter }

rootNavigator

这里我注册了我想要使用的所有元素。

import Foundation
import UIKit
import Swinject

class AppRootNavigator: RootNavigator {

    internal let container: Container
    fileprivate var window: UIWindow?

    init(container: Container) {
        self.container = container
    }

    fileprivate lazy var storyboards: Storyboard = {
        return Storyboard(container: self.container)
    }()

    func installRootViewController(in window:UIWindow) {
        self.window = window
        currentNavigationController = signupController()
        self.window?.rootViewController = currentNavigationController
    }

    fileprivate func signupController() -> UINavigationController {
        let signUpController  =  storyboards.signup.instantiateInitialViewController() as! SignupController

        if let presenter = container.resolve(SignupPresenter.self, argument: self) {
            signUpController.presenter = presenter
        }
        return UINavigationController.init(rootViewController: signUpController)
    }

1 个答案:

答案 0 :(得分:2)

要在navigator工作中更改presenter,您需要明确指定参数类型:

if let presenter = container.resolve(SignupPresenter.self, argument: self as SignupNavigator) {
    signUpController.presenter = presenter
}

但是,您不应该这样做。您只需在SignupNavigator对象范围中注册.container

container.register(SignupNavigator.self) { c in                   
    AppRootNavigator.init(container: container) as SignupNavigator
}.inObjectScope(.container)