HitMan
HitMan

Reputation: 37

Hilt - All modules must be static and use static provision methods or have a visible, no-arg constructor

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

Answers (2)

Jan Itor
Jan Itor

Reputation: 4196

You are getting @ApplicationContext correctly, but there are several other issues.

  • Using the @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.

  • Modules should be objects, not interfaces
  • You don't need any @ApplicationScope annotations on @Singleton scoped bindings

Upvotes: 2

Geek Tanmoy
Geek Tanmoy

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

Related Questions