gpt4 book ai didi

ios - Swinject 中不同 ViewController 的依赖注入(inject)不一致,发布 Swift 3.0 更新 : why?

转载 作者:搜寻专家 更新时间:2023-11-01 07:19:07 25 4
gpt4 key购买 nike

我正在注册一些 Swinject singleton-with-a-small-s (.container) 服务:

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

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

将它们注入(inject)到一些 View Controller 中:

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 )!
}

然后这些 View Controller 以两种不同的方式显示,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 注入(inject)了它的服务,但不幸的是 AnotherViewController 没有。

这在 Swinject 升级到 Swift 3.0 之前可以使用,但现在不行了。请问这是为什么,需要改什么?

谢谢。

更新

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

成功的 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 Storyboard中进行布局。

最佳答案

为了调用 registerForStoryboard,您需要从 SwinjectStoryboard 实例化给定的 Controller ,而不仅仅是 UIStoryboard:

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

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

关于ios - Swinject 中不同 ViewController 的依赖注入(inject)不一致,发布 Swift 3.0 更新 : why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40050100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com