领域未注入匕首

时间:2019-05-29 09:25:36

标签: android dagger-2

在以下代码中,Dagger不会注入字段serviceUtil:

AppController.kt

class App : Application() {
    @Inject
    lateinit var serviceUtil: ServiceUtil

    init {
        DaggerAppComponent
            .builder()
            .build()
            .inject(this)
    }

    override fun onCreate() {
        super.onCreate()
        context = this
    }

    fun startService() {
        serviceUtil.startService()
    }

    companion object {
        lateinit var context: App
    }
}

AppComponent.kt

@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: Application)
}

ServiceUtilModule.kt

@Module
class ServiceUtilModule {
    @Provides
    fun provideServiceUtil() : ServiceUtil {
        return ServiceUtil()
    }
}

在我的主要活动中,我打电话给

App.context.startService()

1 个答案:

答案 0 :(得分:1)

您在此处输入错误

@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: Application)
}

您应该将App类作为参数传递,而不是基本参数。

@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: App)
}