I'm using a Hilt dependency Injection. I have created a PermissionModule, a singleton component and added a PermisisonManager as a @Provides whereas PermissionManager takes a context as a parameter. In PermissionManager, I have injected a constructor along with a context as an constructor argument.
Below is my code snippet: Permission module:
@Module
@InstallIn(SingletonComponent::class)
interface PermissionsModule {
@Provides
@Singleton
@ApplicationScope
fun providesPermissionManager(
@ApplicationContext context: Context
): PermissionManager = PermissionManager(context)
}
Permission manager:
class PermissionManager @Inject constructor(
@ApplicationContext private val context: Context
) {
}
I'm new to Hilt aka DI thing, still learning and trying to use it in my latest app.
While going through the documents and Stackoverflow, I came to know that argument cannot be passed.
I would like to know how can I pass the context to PermissionManager class?
Any help much appreciated.
Thank you.
You need to provide Context from your DI module. Refer the following code.
Note : Here MainApplication is your Application class.
@Provides
@Singleton
fun providesMainApplication(@ApplicationContext context: Context): MainApplication {
return context as MainApplication
}
Also change Permission Module from interface to object.
@Module
@InstallIn(SingletonComponent::class)
object PermissionsModule {
@Provides
@Singleton
@ApplicationScope
fun providesPermissionManager(
@ApplicationContext context: Context
): PermissionManager = PermissionManager(context)
}