Home > front end >  Android Kotlin Hilt: Injecting into object class
Android Kotlin Hilt: Injecting into object class

Time:08-27

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?

CodePudding user response:

You can't inject dependency into Object

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

then u can access like this but for this u need context this for the places where hilt direct injection injection is not supported but u have access to context

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

enter image description here

  • Related