Search code examples
androidkotlindependency-injectiondagger-2

Dagger 2 not injecting, lateinit property not initialized


I am trying to inject Context using Dagger 2. I have seen many other questions on this website related to this but still problem is not solved.

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 where I want to inject Context)

class Manager {

    @Inject
    lateinit var context: Context

    fun foo() {
       context.resources
    }
}

However, I am getting following error at context.resources when Manager().foo() is called from anywhere, say in onCreate() function of MainActivity:

kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized

How to fix this? Why is Dagger not injecting Context?


Solution

  • Try to use constructor injection

    class Manager @Inject constructor(val context: Context) {
    
        fun foo() {
           context.resources
        }
    }
    

    And then in your Activity/Fragment use manager like below:

    @Inject lateinit var manager: Manager