简体   繁体   English

Kotlin Dagger不注射

[英]Kotlin Dagger not inject

I recently move from java to kotlin, and try to implement dagger 2 for dependency injection. 我最近从Java转到kotlin,并尝试实现dagger 2进行依赖注入。

I've add this to my gradle 我已将此添加到我的gradle中

apply plugin: 'kotlin-kapt'

implementation "com.google.dagger:dagger:2.11"
kapt "com.google.dagger:dagger-compiler:2.11"
compileOnly 'javax.annotation:jsr250-api:1.0'

Here is my module 这是我的模块

@Module
class AppModule(val context : Context) {
    @Provides
    @Singleton
    fun provideContext() = context
}

Here is my component 这是我的组件

@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
    fun inject(application: Application)
}

Here is my Application 这是我的申请

class MyApplication : Application() {
    @Inject
    lateinit var context : Context

    lateinit var appComponent : AppComponent

    override fun onCreate() {
        super.onCreate()

        appComponent = DaggerAppComponent.builder()
                .appModule(AppModule(this.applicationContext))
                .build()
        appComponent.inject(this)
    }
}

Here is my activity 这是我的活动

class SplashActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        val context = (applicationContext as MyApplication).context
    }
}

and i get this error 我得到这个错误

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized

This code is working in Java, any idea how to solve this? 这段代码在Java中运行,您知道如何解决吗?

The context property is declared in the MyApplication class, but you're injecting the Application base class here: context属性在MyApplication类中声明,但是您要在此处注入Application基类:

fun inject(application: Application)

... which has no injectable properties. ...没有注射特性。 You have to make an inject method in your component for the specific class instead: 您必须在组件中为特定类创建一个inject方法:

fun inject(application: MyApplication)

Here's an answer explaining how you can use Dagger with hierarchies in more detail. 这是一个答案,解释了如何更详细地将Dagger与层次结构配合使用。

It is not a problem with Dagger. 匕首不是问题。 The error clearly states that you have declared a property with a lateinit but have not initialized it in Kotlin. 该错误清楚地表明您已使用lateinit声明了一个属性,但尚未在Kotlin中对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM