【问题标题】:Android How to dependency inject variables into non activity?Android如何将变量依赖注入到非活动中?
【发布时间】:2023-03-21 06:03:01
【问题描述】:

我有一个 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()
  }
}

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

class Consumer {

   @lateinit var SomeClass someClass;
}

谁能指出我做错了什么?

【问题讨论】:

  • 你得到了没有构造函数的解决方案吗?

标签: android kotlin dagger-2 android-jetpack dagger-hilt


【解决方案1】:

在构造函数中使用注入

class Consumer @Inject constructor(private val someclass:SomeClass){
   //some code
}

【讨论】:

  • 如果我们不想在构造函数中怎么办?
【解决方案2】:

注入非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()
  }
}


更多:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    相关资源
    最近更新 更多