'When do I need to add annotation when I use Hilt as dependency injection?
I'm reading the article Using Hilt in your Android app.
The Code A, Code B and Code C are from the sample project in solution branch.
I'm confused when I should add the Hilt annotation.
In Code A, the parameter
databaseoffun provideLogDaois injected, but the author doesn't add any annotation, but the parameterappContextoffun provideDatabaseis marked with annotation@ApplicationContext, why ?In Code B, the parameter
logDaoofclass LoggerLocalDataSourceis injected, but the author doesn't add any annotation, why?In Code C, I'm told the following content, why isn't the parameter
activityofclass AppNavigatorImpladded any annotation? and you knowApplicationContextis predefined binding too, but the author add annotation@ApplicationContext infun provideDatabasein Code A.
Because an AppNavigator instance is provided in the Activity container , FragmentActivity is already available as a predefined binding.
Code A
@InstallIn(SingletonComponent::class)
@Module
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
return Room.databaseBuilder(
appContext,
AppDatabase::class.java,
"logging.db"
).build()
}
@Provides
fun provideLogDao(database: AppDatabase): LogDao {
return database.logDao()
}
}
Code B
class LoggerLocalDataSource @Inject constructor(private val logDao: LogDao) : LoggerDataSource {
...
}
Code C
class AppNavigatorImpl @Inject constructor(private val activity: FragmentActivity) : AppNavigator {
...
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var navigator: AppNavigator
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
