Swinject - 如何从一个解析器解析同一个控制器两次?

Swinject - how to resolve the same controller twice from one resolver?

import Swinject

class GenericsAssembly: Assembly {
    func assemble(container: Container) {
        container.register(TabBarController.self) { resolver in
            let split1 = resolver.resolve(SplitViewController.self)!
            let split2 = resolver.resolve(SplitViewController.self)!
            split1.tabBarItem = UITabBarItem(title: "1", image: UIImage(named: "icon-notepad"), selectedImage: nil)
            split2.tabBarItem = UITabBarItem(title: "2", image: UIImage(named: "icon-chat"), selectedImage: nil)
            let controller = TabBarController(view: resolver.resolve(TabBarView.self)!)
            controller.viewControllers = [
                tasksSplitViewController,
                threadsSplitViewController
            ]
            return controller
        }
        container.register(SplitViewController.self) { _ in
            return SplitViewController()
        }
        container.register(TabBarView.self) { _ in
            return TabBarView()
        }
    }
}

而且...底部只有一个TabBarItem。为什么?

如果我这样使用它:

let split1 = SplitViewController()
let split2 = SplitViewController()

那么一切都很好。;) 我的实现中的 Swinject 有什么问题?

你可以尝试使用这个:

container.register(SplitViewController.self, name: "second") { _ in
    return SplitViewController()
}

let split2 = container.resolve(SplitViewController.self, name: "second")

容器将return以其他方式解析控制器

如果您需要在单个 register 闭包中解析两个不同的实例,您需要使用 .transient 对象范围:

container.register(SplitViewController.self) { _ in SplitViewController() }
    .inObjectScope(.transient)

您可以在 docs 中阅读有关对象范围的更多信息。

我添加了 "name" 和 "inObjectScope",它对我有用。 检查下面我的工作示例

 var container = Container()

 container.register(ApiClientProtocol.self, name : "ApiClientInstance") { r in ApiClient()}.inObjectScope(.container)

 container.register(LoginViewModelProtocol.self) { r in LoginViewModel(fetcher: r.resolve(ApiClientProtocol.self, name: "ApiClientInstance")!)
  }

以上 LoginViewModel class 有 ApiClient 的单例对象 class