Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always initialize dependency with dagger 2 without any inject or provide

Assume you have such class:

@SomeScope
class ServiceScopeManager {

    @Inject
    Dependency1 dependency1;
    @Inject
    Dependency2 dependency2;

    @Inject
    ServiceScopeManager(){
    }

    @Inject
    void init(){
        //do something really important with dependencies
    }
}
  • This class isn't injected to any other class
  • This class isn't provided to any @Provides method in module

As you can see it's high level class and it, for example, may listens for some events in system and performs releasing of his dependencies.

The problem is that this class won't be ever created, because nothing depends on it.
Can i somehow tell dagger to create dependency always on component creation (for example) not when needed as by default? Or maybe with any other way to achive requirements.

like image 570
Beloo Avatar asked Mar 10 '23 06:03

Beloo


1 Answers

No, Dagger doesn't offer any equivalent of Guice's requestInjection or requestStaticInjection, and if you don't refer to your object, Dagger won't even generate a Factory for it or its dependencies. This is generally a good thing, as it allows you to have a tightly-pruned graph, instead of code-generating Factory implementations for every class on the class path with an @Inject annotation.

You're asking Dagger to do too much here: it's a dependency injection framework and won't manage component life cycle like that. Instead you'll have to perform this initialization in your application logic, maybe by creating a FooComponentInitializer or FooComponentStartup class adjacent to and available through FooComponent. That reduces your code to:

FooComponent fooComponent = DaggerFooComponent.create();
fooComponent.getInitializer().initialize();

...which seems straightforward enough to me.

like image 163
Jeff Bowman Avatar answered Apr 14 '23 14:04

Jeff Bowman