Search code examples
androiddagger-2dagger-hilt

How to pass arguments to Hilt module?


I started to migrate Dagger application to Hilt, first I'm converting AppComponent to Hilt auto-generated ApplicationComponent. Therefore I've added @InstallIn(ApplicationComponent::class) annotation to each module related to this component.

Now I get the following error:

error: [Hilt] All modules must be static and use static provision methods or have a visible, no-arg constructor.

It points to this module:

@InstallIn(ApplicationComponent::class)
@Module
class AccountModule(private val versionName: String) {

    @Provides
    @Singleton
    fun provideComparableVersion(): ComparableVersion {
        return ComparableVersion(versionName)
    }
}

Previously in Dagger, it was possible to pass arguments in the constructor. Looks like Hilt doesn't allow this.

How can I pass arguments to Hilt module?


Solution

  • Unfortunately for now Dagger Hilt is design using monolithic component, where there's only one Application Component and one Activity Component auto generated by it. Refer to https://dagger.dev/hilt/monolithic.html

    Hence the modules for it must be static and use static provision methods or have a visible, no-arg constructor.

    If you put an argument to the module, it will error out stating

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

    From my understanding, you'll trying to get the BuildInfo version number, perhaps the easiest way is to use the provided BuildInfo.VERSION_NAME as below.

    @InstallIn(ApplicationComponent::class)
    @Module
    class AccountModule() {
    
        @Provides
        @Singleton
        fun provideComparableVersion(): ComparableVersion {
            return ComparableVersion(BuildInfo.VERSION_NAME)
        }
    }
    

    If you like to set it yourselves instead of relying on BuildInfo.VERSION_NAME, you can define static const variable that exist differently across flavour.