Reputation: 37
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.
Upvotes: 2
Views: 139
Reputation: 4196
You are getting @ApplicationContext
correctly, but there are several other issues.
@Inject
annotation on the constructor of a class tells Hilt how to provide instances of that class. So you don't need a module to provide PermissionManager
, but you may want to add @Singleton
annotation to it:@Singleton
class PermissionManager @Inject constructor(
@ApplicationContext private val context: Context
) {
}
You need modules when a class can not be simply constructor injected, see more in docs.
@ApplicationScope
annotations on @Singleton
scoped bindingsUpvotes: 2
Reputation: 860
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)
}
Upvotes: 1