1

I have an android application and I would like to perform dependency injection on a class which is not activity or fragment therefore the applicationContext is not present.

@HiltAndroidApp
class App: Application {
  @Inject
  lateinit var analytics: Analytics
  
  override fun onCreate() {
    super.onCreate()
    // other details  
  }

}

My AppModule

@Module
@InstallIn(ApplicationComponent::class)
abstract class AppModule() {
  
  companion object {
    @Provide
    @Singleton
    fun provideSomeClass(): SomeClass = SomeClass()
  }
}

If I try to inject SomeClass in a activity it works fine but not on a non activity class it fails with an error Object is not initialized.

class Consumer {

   @lateinit var SomeClass someClass;
}

Can someone point what I am doing wrong?

kosep26860
  • 45
  • 4

2 Answers2

1

Inject a field of a non-Activity class

To do this you have to create an Interface that will be an @EntryPoint, and pass to that interface the ApplicationContext.

Code sample:

// No annotations here
class Consumer(ctx: Context) { // pass here the Android context

   // Create an Interface (required by @InstallIn)
  @EntryPoint
  @InstallIn(SingletonComponent::class) // this could be implementation specific
  interface Injector {
    fun getSomeClass(): SomeClass // getter that will be injected 
    // you can also define a proper Kotlin Getter here
  }

  // create the injector object
  val injector = EntryPoints.get(ctx, Injector::class.java)
  // retrieve the injected object
  val someObject = injector.getSomeClass()

  suspend fun andFinallyUseIt() {
    someObject.someMethod()
  }
}


More:

Paschalis
  • 11,929
  • 9
  • 52
  • 82
0

Use inject in constructor

class Consumer @Inject constructor(private val someclass:SomeClass){
   //some code
}
Saeid Lotfi
  • 2,043
  • 1
  • 11
  • 23