首页 > 解决方案 > 模块必须设置匕首2

问题描述

我正在尝试使用带有 kotlin 的 dagger 2 创建依赖项。我在运行时收到此错误

引起:java.lang.IllegalStateException:pk.telenorbank.easypaisa.di.modules.RetrofitApiModule 必须设置在 pk.telenorbank.easypaisa.di.DaggerAppComponent$Builder.build(DaggerAppComponent.java:54) at pk.telenorbank.easypaisa .EasypaisaApp.onCreate(EasypaisaApp.kt:22) 在 android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1015) 在 android.app.ActivityThread.handleBindApplication(ActivityThread.java:4834) 在 android.app.ActivityThread.access$1600 (ActivityThread.java:168) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper. java:150) 在 android.app.ActivityThread.main(ActivityThread.java:5659) 在 java.lang.reflect。Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712) 

这是依赖图。

@Module(includes = arrayOf(NetworkModule::class))
class RetrofitApiModule(val retrofitMvpApi: RetrofitMvpApi) {
    @Provides
    @Singleton
    fun provideMvpApi(): RetrofitMvpApi {
        return retrofitMvpApi
    }
}

这是 RetorfitMvpApi

@Singleton
class RetrofitMvpApi @Inject constructor(retrofit: Retrofit) : MvpApi {

    var retrofitService: RetrofitService

    init {
        retrofitService = retrofit.create(RetrofitService::class.java)
    }

    override fun login(source: String) =
            retrofitService.getPosts(source, Constants.API_KEY)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .map { rs -> rs }
                    .doOnError { t -> t.printStackTrace() }


    interface RetrofitService {
        @POST
        fun getPosts(@Query("sources") source: String,
                     @Query("apiKey") key: String): Observable<WSResponse>
    }
}

这是组件。

@Singleton
@Component(modules = arrayOf(AppModule::class, RetrofitApiModule::class))
interface AppComponent {

    fun loginComponent(loginModule: LoginModule) : LoginComponent
}

我在这里做错了什么?我在用dagger 2.15

标签: javaandroiddependency-injectionkotlindagger-2

解决方案


Module如果Module具有默认构造函数, Dagger 将自动为依赖图创建。如果您使用自定义构造函数,则必须在Module构建图形时提供。

对于java代码:

@Module
public class ContextModule {

  private final Context context;

  public ContextModule(Context context) {
      this.context = context;
  }

  @Provides
  @GithubApplicationScope
  @ApplicationContext
  public Context provideContext(){
      return context.getApplicationContext();
  }

}

建筑图:

    githubApplicationComponent = DaggerGithubApplicationComponent.builder()
        .contextModule(new ContextModule(this))
        // not needed as Dagger automatically generate module class with no arguments
        //.networkModule(new NetworkModule())
        .build();

推荐阅读