我需要从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);

最佳答案

我想强调一下, Dagger 不包含任何魔法-它只是纯Java。如果您没有提供所需的信息,则编译器会提示。

如果您查看DaggerNetworkComponent.Builder,您会发现它具有一种称为appComponent(AppComponent component)的方法。这是dagger期望您添加NetworkComponent所依赖的appcomponent的地方。

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

它应该工作。

关于android - 必须设置Dagger ApplicationComponent,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37496432/

10-12 04:19