For types you don’t own the constructor of (like Retrofit or Room, which come from third-party libraries), you provide them via a Hilt Module:
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
@Provides
@Singleton
fun provideApiService(retrofit: Retrofit): ApiService {
return retrofit.create(ApiService::class.java)
}
}
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabase::class.java, "app_db").build()
}
@Provides
fun provideMovieDao(database: AppDatabase): MovieDao = database.movieDao()
}
@InstallIn(SingletonComponent::class) plus @Singleton ensures exactly one Retrofit and one database instance exist for the app’s entire lifetime — replacing the manual thread-safe singleton pattern from the Proficient course’s Room module with a declarative equivalent.
Your Repository can now simply declare what it needs, and Hilt supplies it:
class MovieRepository @Inject constructor(
private val api: ApiService,
private val dao: MovieDao
) { /* ... */ }
- Image
- SKU
- Rating
- Price
- Stock
- Availability
- Add to cart
- Description
- Content
- Weight
- Dimensions
- Additional information