必须设置Dagger ApplicationComponent

时间:2016-05-28 07:31:45

标签: android dagger-2

我需要从OkHttpClient公开我的ApplicationModule,所以我添加到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();

}

所以我在OkHttpClient okHttpClient();添加了ApplicationComponent,如上所示。

现在在我的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);

1 个答案:

答案 0 :(得分:17)

我想强调匕首不含魔法 - 它只是简单的java。如果你没有提供所需的信息,编译器会抱怨。

如果你看一下DaggerNetworkComponent.Builder,你会发现它有一个名为appComponent(AppComponent component)的方法。这是dagger希望您添加NetworkComponent所依赖的appcomponent的地方。

NetworkComponent = DaggerNetworkComponent.builder()
        .NetworkModule(new NetworkModule(this))
        .appComponent(((App)getApplication()).getAppComponent()) // add your appComponent
        .build();

它应该有用。