kotlin 尝试构建应用组件时未解析的引用DaggerApplicationComponent

eqoofvh9  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(165)

我正在使用Android Studio 2022.3.1 Patch 2,我正在尝试创建我的应用组件,但Dagger无法生成我的应用组件。这里是MainApplication.kt

class MainApplication : Application() {

    val applicationComponent: ApplicationComponent =
        DaggerApplicationComponent.builder().applicationModule(ApplicationModule(this)).build()

    @Inject
    lateinit var indoor: Indoor

    override fun onCreate() {
        super.onCreate()
        applicationComponent.inject(this)
    }
}

我的ApplicationComponent

import dagger.Component
import javax.inject.Singleton

@Singleton
@Component(modules = [ApplicationModule::class])
interface ApplicationComponent {
    @ApplicationContext
    fun context(): Context
    fun application(): Application
    fun  inject(application: MainApplication)
}

同样在我的build.graddle中,依赖关系看起来像这样

//Dagger
    implementation("com.google.dagger:dagger:2.48.1")
    implementation("com.google.dagger:dagger-android-support:2.48.1") 
    annotationProcessor("com.google.dagger:dagger-android-processor:2.48.1")
    annotationProcessor("com.google.dagger:dagger-compiler:2.48.1")

我尝试使用
kapt“com.google.dagger:dagger-compiler:2.x.x
但是没有用
编辑:这是我的ApplicationModule代码

import dagger.Module

导入匕首。提供了导入javax.inject.Singleton
@Module类ApplicationModule(private瓦尔application:应用程序){

@Provides
@ApplicationContext
fun provideContext(): Context = application

@Provides
fun provideApplication(): Application = application
zpqajqem

zpqajqem1#

为您的ApplicationModule试试这个

@Module 
class ApplicationModule (private val application: Application) {

@Provides
fun provideApplication(): Application = application

}

仔细检查Indoor类是否有@Inject注解的构造函数:

class Indoor @Inject constructor(...){
    ...
}

ApplicationComponent

@Singleton
@Component(modules = [ApplicationModule::class])
interface ApplicationComponent {
    fun inject(application: MainApplication)
}

还可以通过ApplicationModuleIndoor传入对象图

@Module 
class ApplicationModule (private val application: Application) {

@Provides
fun provideApplication(): Application = application
    
@Provides
//@Singleton
fun provideIndoor(application: Application) = Indoor(application)

}

相关问题