Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 454
Micer Avatar asked Jul 02 '20 08:07

Micer


2 Answers

@InstallIn(ApplicationComponent::class)
@Module
class AccountModule {
    @Provides
    @Singleton
    fun provideComparableVersion(application: Application): ComparableVersion {
        return ComparableVersion((application as MyApplication).versionName)
    }
}

If you don't want to see MyApplication, then you can use an interface.

like image 123
EpicPandaForce Avatar answered Oct 07 '22 10:10

EpicPandaForce


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.

like image 26
Elye Avatar answered Oct 07 '22 11:10

Elye