Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inject dependancies of common parent ViewController #123

Open
busu90 opened this issue Jun 6, 2019 · 3 comments
Open

Inject dependancies of common parent ViewController #123

busu90 opened this issue Jun 6, 2019 · 3 comments

Comments

@busu90
Copy link

busu90 commented Jun 6, 2019

All of my ViewControllers have a common parent, lets say P. Is there a way to inject the parameters for this common parent whitout having to do this in each individual chiald view controller ?

@busu90 busu90 changed the title Inject dependancies of common parent ViewCOntroller Inject dependancies of common parent ViewController Jun 6, 2019
@jakubvano
Copy link
Member

Assuming that common dependencies are injected as properties, you might be able to do it by implementing a custom container behavior, something along the lines of

final class ParentViewControllerBehavior: Behavior {
    func container<Type, Service>(
        _ container: Container,
        didRegisterType type: Type.Type,
        toService entry: ServiceEntry<Service>,
        withName name: String?
    ) {
        guard type is ParentViewController.Type else { return }
        entry.initCompleted { resolver, vc in
            (vc as! ParentViewController).commonDependency = resolver.resolve(Any.self)
        }
    }
}

container.addBehavior(ParentControllerBehavior())
container.register(ChildViewController.self) { /* only need to inject specific dependencies */ }

This basically checks every registration if the type inherits from ParentViewController, and appends initCompleted setup to it.

@Capotasto
Copy link

Capotasto commented Feb 10, 2021

@jakubvano Sorry for this late question. I tried above code for injecting some dependencies into my BaseViewController that is inherited by ViewControllers.

  1. type is always UIViewController.Type and never be BaseViewController.Type so always return function. How to get specific Child ViewController Type?
  2. I use storyboardInitCompleted to register my ViewControllers to the Container. Should I register again like your last line?

@Capotasto
Copy link

I think I figured out by my self. The code worked perfectly below

       guard type is UIViewController.Type else { return }
        entry.initCompleted { resolver, vc in
            (vc as! ParentViewController).commonDependency = resolver.resolve(Any.self)
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants