iosswiftswinject

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

And... there is only one TabBarItem at the bottom. Why?

If I use it like this:

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

then everything is fine.;) What is wrong with Swinject here in my implementation?


Solution

  • You could try use this:

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

    in other way container will return already resolved controller