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

时间:2018-08-24 08:12:06

标签: ios swift swinject

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有什么问题?

3 个答案:

答案 0 :(得分:1)

您可以尝试使用:

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

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

以其他方式,容器将返回已解析的控制器

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

我同时添加了“名称”和“ 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类上方具有ApiClient类的单例对象