Search code examples
swiftdependency-resolverswinject

Swinject: generate instances of any object (for not registered object, ViewModel, etc...)


is possible to resolve/ create a new instace of object thats are not registered in Swinject container? In Unity dependency injection for c# (from Microsoft) is it.

I Want to resolve viewModel class, that have dependence for some protocols. For example: I have registred IFileManager in container:

container.register(IFileManager.self) { _ in FileManager() }.inObjectScope(ObjectScope.container)

and me viewModel have dependece for IFileManager

class AwesomeViewModel{
init (fileManager: IFileManager) {
    ....
}}

now i want to create new instance of AwesomeViewModel using Swinject resolver, and I want all the dependencies to be added to the init, but it doesn't work

viewModel = AppDelegate.container.resolve(AwesomeViewModel.self)

and ViewModel is nil


Solution

  • No, Swinject is not able to infer which initialisation method you expect to be used for instantiation of AwesomeViewModel. You need to explicitly define it first:

    container.register(AwesomeViewModel.self) {
        AwesomeViewModel(fileManager: $0.resolve(IFileManager.self)!)
    }
    

    Admittedly, this might get quite cumbersome if you have classes with many dependencies. If that becomes a problem, I suggest you check out the SwinjectAutoregistration extension. It enables you to write:

    container.autoregister(AwesomeViewModel.self, initializer: AwesomeViewModel.init)