Johann
Johann

Reputation: 29867

Field not being injected with Dagger

In the following code, the field serviceUtil is not being injected by Dagger:

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()
    }
}

From my main activity I call:

App.context.startService()

Upvotes: 0

Views: 32

Answers (1)

grig
grig

Reputation: 847

You mistyped here

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

You should pass you App class as argument, not the basic one.

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

Upvotes: 2

Related Questions