【发布时间】: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