我试图使用dagger 2和kotlin创建依赖关系。我在运行时得到了这个错误
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) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1015) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4834) at android.app.ActivityThreadAndroid.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(本地方法)Com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)在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
发布于 2018-05-24 17:27:11
provideMvpApi方法应该以retrofitMvpApi为实例,并返回它的接口:
@Module(includes = arrayOf(NetworkModule::class))
class RetrofitApiModule() {
@Provides
@Singleton
fun provideMvpApi(val retrofitMvpApi: RetrofitMvpApi): MvpApi {
return retrofitMvpApi
}
}发布于 2018-05-24 17:37:29
如果Module具有默认构造函数,Dagger将自动为依赖图创建Module。如果使用自定义构造函数,则必须在构建图形时提供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();https://stackoverflow.com/questions/50514896
复制相似问题