Reputation: 4391
I have some questions regarding dagger2 which i find hard to understand. This code:
@Module
public class AppModule {
private MainApplication applicationContext;
@Inject
public AppModule(MainApplication context){
this.applicationContext = context;
}
@Provides
@Singleton
StuffA provideStuffA(){
return new StuffA();
}
@Provides
@Singleton
StuffB provideStuffB(StuffA){
return new StuffB(stuffA);
}
}
And in the application class:
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
My first question is:
Second question:
Final question
PS. I'm sorry if this is really basic stuff, but i find the documentation very poor and lack of examples as well. Thanks in advanced
Upvotes: 1
Views: 2148
Reputation: 13600
Answer 1
You just split them in two separate modules. Dagger will build the graph and when at some point provideStuffB()
is called it will inject it with StuffA
. Btw I think there is small syntax error in the provide
method and it should be (stuffA parameter was missing):
@Provides
@Singleton
StuffB provideStuffB(StuffA stuffA){
return new StuffB(stuffA);
}
Answer 2
Yes, that is the usual way. Just after you create the graph (in onCreate()
) you inject this
(the application). Please note there is a subtle caveat when in comes to unit tests with this approach - Application
object will be created even before setUp()
method is called so you will be unable to set/swap your test Component (and you will end up always with your default Component). The solution is to use lazy initialization of the graph, i.e. when first activity (or service, or BroadcastReceiver
, etc.) calls getApplication().getInjector(this)
you will have to create the graph at that point.
Answer 3
You usually have one top Component
that contains all the modules and subcomponents. It is (have to be) able to inject all activities. De facto the top component is used to generate the graph. Here is an example from real app:
@Component(modules = {IzgubenoDaggerModule.class,
AcraDaggerModule.class,
AppInfoDaggerModule.class,
SessionDaggerModule.class,
ComponentManagerDaggerModule.class,
NetworkInfoProviderDaggerModule.class,
DeviceInfoProviderDaggerModule.class,
KhRestExchangeManagerDaggerModule.class
})
@Singleton
public interface IzgubenoDaggerComponent extends GgLibDaggerComponent {
void inject(IzgubenoApplication app);
void inject(Act_Main act);
void inject(Act_ContactDetails act);
void inject(Act_MyPets act);
void inject(Act_PetEdit act);
void inject(Act_PetManage act);
void inject(Act_PetPics act);
//...
GgLibDaggerComponent newGgLibDaggerComponent(HttpsDaggerModule httpsMod,
KhRestDaggerModule khrestMod,
AppInfoDaggerModule appInfoMod,
GgServerDaggerModule ggServMod,
GgClientDaggerModule ggClientMod);
//...
}
Upvotes: 1