Search code examples
androidkotlindependency-injectiondagger-hilt

Android + Kotlin + Hilt: Injecting into object class


I will focus in injecting Context, but my question applies to whatever dependency it is, like a repository or service class.

I have an object as follows:

object MyObject {

    lateinit var appContext: Context

    doWhatever(appContext: Context){ => This is where I need context
    }

    fun myMethod() {
        val baseClass = BaseClass()
        doWhatever(appContext)
    }
}

I already know Hilt cannot inject into objects, but it can inject into classes, so I'm trying the next approach.

object MyObject : ProviderClass() {

    doWhatever(appContext: Context){
    }

    fun myMethod() {
        val baseClass = BaseClass()
        doWhatever(appContext)
    }
}

abstract class ProviderClass {

    @Inject
    lateinit var appContext: Context
}

As you see, I'm trying to do field injection into ProviderClass and making the field available through inheritance, but it is also failing with "lateinit var appContext has not been initialized".

This is where I provide dependencies:

@Module
@InstallIn(SingletonComponent::class)
object Dependencies {

    @Singleton
    @Provides
    fun provideContext(@ApplicationContext appContext: Context): Context {
        return appContext
    }
}

What's wrong? How can I inject any dependency into an object?


Solution

  • You can't inject dependency into Object

    @EntryPoint
    @InstallIn(SingletonComponent::class)
    interface SomeInterface{
        val dep: YourDependecyClass
    }
    

    but you can access dependencies like this, to do this you need context in places where hilt direct injection is not supported yet have access to context

    val x:SomeInterface = EntryPointAccessors.fromApplication(applicationContext, SomeInterface::class.java)
    

    Below image is not directly related to answer, just a reference for the discussion we had in comment section enter image description here