如果没有kotlin

时间:2017-10-24 07:09:53

标签: android dependency-injection kotlin dagger-2

我在Kotlin中使用Dagger进行依赖注入。现在这里是必要的类

ActivityModule

@Module class ActivityModule (val activity : Activity){
    @Provides
    @ActivityContext
    fun provideContext() : Context{
        return activity
    }
}

ActivityComponent

@PerActivity
@Component(dependencies = arrayOf(ApplicationComponent::class), modules = arrayOf(ActivityModule::class))
interface ActivityComponent {
    fun inject(activity: MainActivity)
}

MainActivity

@Inject @ActivityContext lateinit var context:Context
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerActivityComponent.builder()
.applicationComponent(MainApplication.getInstance().getApplicationComponent()).activityModule(ActivityModule(this)).build()
.inject(this);

现在我收到以下错误

error: android.content.Context cannot be provided without an @Provides- or @Produces-annotated method.
e: 

e:     public abstract void inject(@org.jetbrains.annotations.NotNull()
e:                          ^
e:       android.content.Context is injected at
e:           app.feed.com.ui.MainActivity.context
e:       app.feed.com.ui.MainActivity is injected at
e:           app.feed.com.injection.component.ActivityComponent.inject(p0)

我在java中使用相同的代码并且工作正常但是在kotlin中它给出了错误,同样ApplicaionComponent依赖项工作正常。同时我使用以下版本的gradle和kotlin

buildscript {
    ext.kotlin_version = '1.1.2-3'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

请帮我弄清楚我做错了什么

1 个答案:

答案 0 :(得分:3)

您注入了属性

@Inject @ActivityContext lateinit var context: Context

仅使用@ActivityContext注释该属性。所以 Dagger 正在为没有任何限定符的简单Context寻找提供者。相反,你必须用它来注释字段

@Inject @field:ActivityContext lateinit var context: Context