首页 > 解决方案 > Android如何依赖注入变量到非活动中?

问题描述

我有一个 android 应用程序,我想对一个不是活动或片段的类执行依赖注入,因此 applicationContext 不存在。

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

}

我的应用模块

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

如果我尝试在活动中注入SomeClass它可以正常工作,但不能在非活动类上失败,并出现错误Object is not initialized

class Consumer {

   @lateinit var SomeClass someClass;
}

有人可以指出我做错了什么吗?

标签: androidkotlindagger-2android-jetpackdagger-hilt

解决方案


注入非Activity类的字段

为此,您必须创建一个Interface将成为 的@EntryPoint,并将ApplicationContext.

代码示例:

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


更多的:


推荐阅读