Middle+
How to provide different instances of the same class in Dagger Hilt?
sobes.tech AI
Answer from AI
To provide different instances of the same class in Dagger Hilt, you can use qualifiers (@Named or custom ones).
-
Creating qualifiers:
- Use
@Namedfor simple cases, specifying a string name. - Create your own custom qualifier annotations for more complex scenarios or better semantics.
// Example of a custom qualifier @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class ProductionApi @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class TestApi - Use
-
Binding different instances using qualifiers:
- In Hilt modules (
@Module), inside classes with@Providesor@Binds, use qualifier annotations for methods returning instances.
@Module @InstallIn(SingletonComponent::class) // Example scope object AppModule { @Provides @Singleton // Example scope @Named("개발") // @Named qualifier for the "Development" instance fun provideDevRepository(): Repository { return Repository("개발 환경") // Different instance or configuration } @Provides @Singleton // Example scope @Named("운영") // @Named qualifier for the "Production" instance fun provideProdRepository(): Repository { return Repository("운영 환경") // Different instance or configuration } // Using custom qualifiers @Provides @Singleton @ProductionApi fun provideProductionService(): MyService { return MyService("Production API endpoint") } @Provides @Singleton @TestApi fun provideTestService(): MyService { return MyService("Test API endpoint") } } - In Hilt modules (
-
Injecting a specific instance:
- In places where you need to inject a dependency (
@AndroidEntryPoint), annotate the field or constructor parameter with the appropriate qualifier.
@AndroidEntryPoint // For example, Fragment or Activity class MyFragment : Fragment() { @Inject @Named("개발") // Injecting the "Development" instance lateinit var devRepository: Repository @Inject @Named("운영") // Injecting the "Production" instance lateinit var prodRepository: Repository @Inject @ProductionApi // Injecting the production instance with a custom qualifier lateinit var productionService: MyService // ... usage of dependencies ... } - In places where you need to inject a dependency (