I'm building an application which uses Dagger 2.
So, my application component looks like this:
@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
// Exported for child-components.
Application application ();
final class Initializer {
public static ApplicationComponent init (Application app) {
return DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(app)).build();
}
private Initializer () {
} // No instances.
}
ConnectorComponent plus(ConnectorModule module);
... injections
}
This is scoped with @Singleton, so it's unique for the app lifetime.
Then I have another component, which should be able to use all dependencies provided by the above component, but provide it's dependencies with a @PerActivity scope:
@Scope
@Retention(RUNTIME)
public @interface PerActivity {}
And looks like this
@PerActivity
@Subcomponent(modules = ConnectorModule.class)
public interface ConnectorComponent {
... injections
}
The problem is. How can I make sure the everything that is provided with @Singleton will be passed as Singletons on the dependencies to ConnectorModule? Another thing, how can I make sure that the method plus
in ApplicationComponent will always add a new Module (the @PerActivity) that I want?
Last of all, can anybody think of a strategy to use this in all activites (which makes sense to be used with @PerAcitivity scope) and not having to call plus
every time with a new ConnectorModule?
How can I make sure the everything that is provided with @Singleton will be passed as Singletons on the dependencies to ConnectorModule?
Dagger will ensure that any @Singleton
-annotated type or @Provides
method in ApplicationModule
will be provided only once during the lifetime of the DaggerApplicationComponent
you build, even when a binding in ConnectorComponent
uses it.
how can I make sure that the method plus in ApplicationComponent will always add a new Module (the @PerActivity) that I want?
I'm not sure what you're asking here. When you call plus
, you'll have to pass in an instance of ConnectorModule
yourself.
can anybody think of a strategy to use this in all activites (which makes sense to be used with @PerAcitivity scope) and not having to call plus every time with a new ConnectorModule?
Does ConnectorModule
take arguments in its constructor? If not, you can leave it out of the plus
method's arguments, and Dagger will construct one for you.
However, you still have to call the plus
method in order to get an instance of the subcomponent for the activity. That's how you get the @PerActivity
scope to work: there's an instance of ConnectorComponent
, and that scope is tied to the lifetime of that instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.