【问题标题】:Jetpack Compose: How to Provide Context for Dagger/HiltJetpack Compose:如何为 Dagger/Hilt 提供上下文
【发布时间】:2022-10-15 17:56:42
【问题描述】:

所以我意识到在测试我的实际应用程序时我仍然需要提供Context(在运行实际测试时我只使用了val appContext = InstrumentationRegistry.getInstrumentation().targetContext所以我有点忘了它。

但现在我在模拟器中运行实际的应用程序并在启动时收到此错误:error: [Dagger/MissingBinding] android.content.Context cannot be provided without an @Provides-annotated method.

我的 DI 对象如下所示:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Provides
    @Singleton
    fun provideShotTrackerDatabase(context: Context): ShotTrackerDbAdapter {
        val db = ShotTrackerDbAdapter(context)

        return db.open()
    }

    @Provides
    @Singleton
    fun provideShotTrackerRepository(db: ShotTrackerDbAdapter): ShotTrackerRepository {
        return ShotTrackerRepository(db)
    }
}

当然,我的 ViewModel 非常标准,这是声明:

@HiltViewModel
class FirearmsViewModel @Inject constructor (private val shotTrackerRepository: ShotTrackerRepository) : ViewModel() {

我想我有点假设这已经提供了,因为它可以通过 LocalContext.current 在 Composable 中轻松访问,但事实并非如此。

【问题讨论】:

    标签: kotlin dependency-injection android-jetpack-compose dagger-hilt


    【解决方案1】:

    然而,在写这个问题时,我偶然发现了答案。在Context 前面使用ApplicationContext 注释:

    @Provides
        @Singleton
        fun provideShotTrackerDatabase(@ApplicationContext context: Context): ShotTrackerDbAdapter {
            val db = ShotTrackerDbAdapter(context)
    
            return db.open()
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 2021-08-23
      • 2018-03-21
      • 2021-05-14
      • 1970-01-01
      • 2020-03-03
      相关资源
      最近更新 更多