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
}
}
@Provides
method in moduleAs 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With