问题描述
我在我的android项目中使用dagger2 2.16版本进行依赖注入。我研究了许多示例,尽管我没有类似的方法,但出现了循环依赖错误。
我的源代码;
AppComponent.kt
I am using dagger2 2.16 version for dependency injection inside mine android project. I examine a lot of examples, and although I do not have a similar approach I get the error of "circular dependency".Mine source code;AppComponent.kt
@Singleton
@Component(
modules = [
AndroidSupportInjectionModule::class,
AppModule::class,
ActivityBuilderModule::class]
)
interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
fun inject(app: App)
}
App。 kt
class App : Application(), HasActivityInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>
override fun onCreate() {
super.onCreate()
AppInjector.init(this)
initOneSignal()
}
private fun initOneSignal() = OneSignal.startInit(this).setNotificationOpenedHandler(CustomNotificationOpenedHandler()).inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification).init()
override fun activityInjector() = dispatchingAndroidInjector
}
ActivityBuilderModule.kt
@Module
abstract class ActivityBuilderModule {
@ContributesAndroidInjector
abstract fun contributeSplashActivity(): SplashActivity
}
AppModule.kt
@Module(includes = [(ViewModelModule::class)])
class AppModule {
@Singleton
@Provides
fun provideContext(app: Application): Context = app.applicationContext;
@Singleton
@Provides
fun provideApiService(client: OkHttpClient): ApiService {
return Retrofit.Builder()
.baseUrl(Constants.baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ApiService::class.java)
}
@Singleton
@Provides
fun provideOkHttpClient(interceptor: HttpLoggingInterceptor): OkHttpClient {
return OkHttpClient.Builder().addInterceptor(interceptor).build()
}
@Singleton
@Provides
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
return interceptor
}
}
如果我从AppComponent中删除ActivityBuilderModule,则项目编译不会出现问题。但是,如果您添加到模块部分,则项目将出现以下错误。
If I remove the ActivityBuilderModule from the AppComponent, the project is compiled without problems. But if you add to the modules section, the project gives the error below.
请帮助我。
推荐答案
也可能会出现上述错误消息,因为未将kotlin stdlib声明为依赖项。所以添加例如在build.gradle(.kts)文件中的 implementation( org.jetbrains.kotlin:kotlin-stdlib:1.3.60)
可能也有帮助。
The above mentioned error message might also appear, because kotlin stdlib is not declared as dependency. So adding e.g. implementation("org.jetbrains.kotlin:kotlin-stdlib:1.3.60")
in your build.gradle(.kts) file might also help.
这篇关于Dagger2循环依赖性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!