Dagger 2未注入,lateinit属性未初始化

问题描述 投票:0回答:1

我正在尝试使用Dagger 2注入Context。我在此网站上看到了许多与此相关的其他问题,但仍然无法解决问题。

AppComponent.kt:

@Singleton
@Component(
    modules = [
        AppModule::class
    ]
)
interface AppComponent {
    fun context(): Context
    fun inject(context: Context)
}

AppModule.kt:

@Module
class AppModule(private val context: Context) {

    @Provides
    @Singleton
    fun providesApplicationContext(): Context = context
}

MainApp.kt:

class MainApp : Application() {
    lateinit var appComponent: AppComponent

    override fun onCreate() {
        super.onCreate()
        appComponent = initDagger()
        appComponent.inject(this)
    }

    private fun initDagger() = DaggerAppComponent.builder()
        .appModule(AppModule(this))
        .build()
}

Manager.kt :(我要在其中注入上下文的类)

class Manager {

    @Inject
    lateinit var context: Context

    fun foo() {
       context.resources
    }
}

但是,当从任何地方调用context.resources时,例如在Manager().foo()onCreate()函数中,当我在MainActivity处出现以下错误:

kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized

如何解决?为什么Dagger不注入Context

android kotlin dependency-injection dagger-2
1个回答
0
投票

尝试使用constructor注射

class Manager @Inject constructor(val context: Context) {

    fun foo() {
       context.resources
    }
}

然后在您的Activity/Fragment中使用manager,如下所示:

@Inject lateinit var manager: Manager
© www.soinside.com 2019 - 2024. All rights reserved.