1

我正在注册一些Swinject带有小号(.container)的单例服务:

defaultContainer.register( SomeService.self )
{
    _ in SomeService() 
}.inObjectScope( .container )

defaultContainer.register( AnotherService.self )
{
    responder in AnotherService(
        someService: responder.resolve( SomeService.self )!
    )
}.inObjectScope( .container )

将它们注入到一些视图控制器中:

defaultContainer.registerForStoryboard( SomeViewController.self )
{
    resolvable, viewController in
    viewController.someService = resolvable.resolve( SomeService.self )
    viewController.anotherService = resolvable.resolve( AnotherService.self )!
}

defaultContainer.registerForStoryboard( AnotherViewController.self )
{
    resolvable, viewController in
    viewController.someService = resolvable.resolve( SomeService.self )
    viewController.anotherService = resolvable.resolve( AnotherService.self )!
}

然后这些视图控制器以两种不同的方式显示,SomeViewController如下所示:

DispatchQueue.main.async
{
    self.performSegue( withIdentifier: "somePageSegue", sender: nil )
}

像这样AnotherViewController

let anotherViewController = UIStoryboard(
    name: "Main"
    , bundle: nil
).instantiateViewController( withIdentifier: "anotherSegue" )

present( anotherViewController, animated: true, completion: nil )

SomeViewController得到它的服务注入,但不幸AnotherViewController的是没有。

这在升级到 Swift 3.0 之前曾经可以工作Swinject,但现在不行。请问这是为什么,需要改变什么?

谢谢你。

更新

不幸的是,我既不熟悉Swinject's 的底层代码库,也没有时间熟悉自己,但是通过挖掘表面下发生的事情,我发现了以下内容,希望这对任何可能比我更了解它的人有用:

成功的 VC DI:

// once into:
private func injectDependency(to viewController: UIViewController)

// then:
defaultContainer.registerForStoryboard( SomeViewController.self )

// then many times into:
public func _resolve<Service, Factory>(name: String?, option: ServiceKeyOptionType? = nil, invoker: (Factory) -> Service) -> Service?

失败的 VC DI:

// repeatedly going from:
private func injectDependency(to viewController: UIViewController)

// to:
public func _resolve<Service, Factory>(name: String?, option: ServiceKeyOptionType? = nil, invoker: (Factory) -> Service) -> Service?

// and back again,
// then twice into:
public override func instantiateViewController(withIdentifier identifier: String) -> UIViewController

补充说明:

失败的 VC 是 TabBarController 中的 UIViewController,两者都已在标准 XCode 故事板中布局。

4

2 回答 2

1

事实证明这是一个错误,在此处详细说明:https ://github.com/Swinject/Swinject/issues/177 。目前正在进行修复。一旦我知道更多,我会报告。

更新

这显然是固定的。

于 2016-10-19T08:21:29.130 回答
1

为了registerForStoryboard被调用,您需要实例化给定的控制器SwinjectStoryboard,而不仅仅是UIStoryboard

let anotherViewController = SwinjectStoryboard.create(name: "Main", bundle: nil)
    .instantiateViewController(withIdentifier: "anotherSegue")

present(anotherViewController, animated: true, completion: nil)
于 2016-10-15T08:35:19.110 回答