Integration with Retrofit¶
If you use Retrofit to define your API services, you can use the @AutoProvideService
to automatically contribute your services to the Dagger graph.
Firstly add the required dependency:
dependencies {
implementation("se.ansman.dagger.auto:retrofit:1.5.0")
kapt("se.ansman.dagger.auto:compiler:1.5.0")
// or if you use KSP
ksp("se.ansman.dagger.auto:compiler:1.5.0")
}
Then annotate your service with @AutoProvideService
:
You'll also need to provide a Retrofit instance to the component you want to inject the service into:
@Module
@InstallIn(SingletonComponent::class)
object RetrofitModule {
@Provides
@Singleton
fun provideRetrofit(): Retrofit = Retrofit.Builder()
// Perform any setup you need
.baseUrl("https://api.example.com/")
.addConverterFactory(SomeConverterFactory.create())
.build()
}
Changing the target component¶
By default, services are installed in the SingletonComponent
. If you'd like to change this you can do so by specifying the inComponent
parameter:
@AutoProvideService(inComponent = SomeOtherComponent::class)
class ApiService {
// Service methods
}
Qualifiers¶
If you have multiple retrofit instances and use qualifiers to differentiate them, you can specify the qualifier on the service:
Making the service scoped or reusable¶
By default, provided service is unscoped and will be created every time it is injected. Retrofit caches the parsing of services so this is not an expensive operation, but it injected frequently you can avoid this by annotating your service with a scope or @Reusable
: