
🧑🏻💻 When a Module Is Not Required: Concrete Classes
In Hilt/Dagger, concrete classes with an @Inject constructor can be injected automatically.
class ApiClient @Inject constructor()
class UserRepository @Inject constructor(
private val api: ApiClient
)
Point:
If the class can be instantiated directly, a Module is not required.
🧑🏻💻 When a Module Is Required (1): Interfaces
When injecting an interface, Hilt cannot determine which implementation to use.
You need to specify it explicitly using @Binds inside a Module.
interface Logger {
fun log(msg: String)
}
class ConsoleLogger @Inject constructor() : Logger
@Module
@InstallIn(SingletonComponent::class)
interface LoggerModule {
@Binds
fun bindLogger(impl: ConsoleLogger): Logger
}
Point:
Interfaces always require a Module.
🧑🏻💻 When a Module Is Required (2): External Libraries
External libraries typically do not have @Inject constructor.
You must provide the creation logic inside a Module.
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
fun provideClient(): OkHttpClient = OkHttpClient.Builder().build()
}
Point:
You make external classes injectable by defining how to create them in a Module.
🧑🏻💻 Summary
- Your own concrete classes → auto-injectable
- Interfaces & external libraries → Module required
- Multiple implementations or singleton handling → use @Qualifier, @Named, @Singleton
👉 Dagger/HiltでModuleが必要か一目でわかるようにパターン化する
Related Categories : Android・Developmemt・Recommended