Here i created application class dependency. now i want to access
@Module
@InstallIn(SingletonComponent::class)
class MyApplicationModule {
@Provides
fun providesMainApplicationInstance(application: MainApplication): MainApplication =
application
}
My application class is:
@HiltAndroidApp
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
}
fun printData(){
Log.d("Test","Awesome print data")
}
}
i want to call printData() function from the activity. i have used field injection to access application class but it gives error...
@Inject lateinit var mainApplication: MainApplication
ERROR
[Dagger/DependencyCycle] Found a dependency cycle:
MainApplication is injected at MyApplicationModule.providesMainApplicationInstance(application)
CodePudding user response:
This should work:
@Module
@InstallIn(SingletonComponent::class)
class MyApplicationModule {
@Provides
fun providesMainApplicationInstance(@ApplicationContext context: Context): MainApplication {
return context as MainApplication
}
}
Hilt can inject application context. You need to simply cast it.
Let me know if it's good.