Issue
Basically I'm migrating from dagger to hilt. So I must need to remove this argument class ApplicationModule(application: MyApplication) {
So, there are few places that I want to pass application class object from my dagger hilt module. few are 3rd part library as well.
Code:
@InstallIn(SingletonComponent::class)
@Module
class ApplicationModule(application: MyApplication) {
private val application: MyApplication = application
....
@Provides
@Singleton
fun provideGoogleSignInClient(): GoogleSignInClient {
val mGoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(application.getString(R.string.default_web_client_id))
.requestProfile()
.requestEmail()
.build()
return GoogleSignIn.getClient(application, mGoogleSignInOptions)
}
like this many places are there. So how can I achieve this?
EDIT:
@Provides
@Singleton
fun provideUserService(): NewUserService {
return NewUserService(application)
}
class NewUserService @Inject constructor(@ApplicationContext context: Context) : BaseServices(context) {
Solution
You could use Hilt's @ApplicationContext
annotation to substitute your application
with the application context. Make the following change:
@Provides
@Singleton
fun provideGoogleSignInClient(@ApplicationContext applicationContext: Context): GoogleSignInClient {
val mGoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(applicationContext.getString(R.string.default_web_client_id))
.requestProfile()
.requestEmail()
.build()
return GoogleSignIn.getClient(applicationContext, mGoogleSignInOptions)
}
To address your further question. When you are providing your class within the module, you do not need to also instruct Dagger to @Inject it. Your code will be like so:
@Provides
@Singleton
fun provideUserService(@ApplicationContext context: Context): NewUserService {
return NewUserService(context)
}
And your class:
class NewUserService (context: Context) : BaseServices(context)
Constructor injection is useful in the case where Dagger already knows how to provide your dependency classes. For example you have the following:
@Provides
@Singleton
fun provideMyClass(@ApplicationContext applicationContext: Context): MyClass {
val someField = funToReturnValue(applicationContext)
return MyClass.initialise(someField)
}
Then when you have another class that needs MyClass
, you can just use constructor injection because Dagger already knows how to construct MyClass. You would do:
class MySecondClass @Inject constructor(val myClass: MyClass)
Answered By - Filip Petrovski
Answer Checked By - Senaida (JavaFixing Volunteer)