4
我需要從ApplicationModule
公開我的OkHttpClient
,所以我添加到ApplicationComponent
。事情是這樣的:Dagger ApplicationComponent必須設置
@Module
public class ApplicationModule {
@Provides @Singleton
public OkHttpClient provideOkHttpClient() {
final OkHttpClient.Builder client = new OkHttpClient.Builder();
return client.build();
}
@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
OkHttpClient okHttpClient();
}
所以我在ApplicationComponent
添加OkHttpClient okHttpClient();
,你可以看到正上方。
現在在我的NetworkModule
我用它喜歡:
@Module
public class NetworkModule {
@Provides @ActivityScope
public ProjectService provideProjectService(OkHttpClient client) {
return new ProjectService(client);
}
@Component(dependencies = {ApplicationComponent.class}, modules = {NetworkModule.class})
@ActivityScope
public interface NetworkComponent {
void inject(@NonNull MyActivity myActivity);
}
但現在,當我得到一個運行時錯誤:
Caused by: java.lang.IllegalStateException: css.test.demo.ApplicationComponent must be set
at css.test.demo.main.projects.network.DaggerNetworkComponent$Builder.build(DaggerNetworkComponent.java:102)
at css.test.demo.main.projects.MyActivity.onCreate(MyActivity.java:159)
at android.app.Activity.performCreate(Activity.java:6237)
,這裏是我是如何建造起來MyActivity:
NetworkComponent = DaggerNetworkComponent.builder()
.NetworkModule(new NetworkModule(this))
.build();
NetworkComponent.inject(this);
如果我不希望一些類的應用程序模塊例如在一個類中完全依賴,那我該如何在網絡模塊中包含applicationModule,但其他類只需要網絡模塊來完成依賴關係。請幫忙。 –
@eCDroid如果網絡模塊依賴於應用程序模塊,而其他模塊依賴於網絡模塊,那麼這個其他模塊也取決於應用程序模塊,但您總是可以拆分/重構模塊或創建新模塊。 –