Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Hilt from picking dependency from a library?

Okay, let's make this simple.

I have created a simple library called my-network-library with two classes in it. First one is a Hilt module called BaseNetworkModule

@Module
@InstallIn(ApplicationComponent::class)
object BaseNetworkModule {

    // Client
    @Singleton
    @Provides
    fun provideOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            // my default okhttp setup goes here 
            .build()
    }
}

and the second one is a simple class.

class MyAwesomeClass {
    fun doMagic() {
        // magic code goes here
    }
}

Now I want to use MyAwesomeClass in one of my App. So I added the dependency in the app.

implementation "com.theapache64:my-awesome-library-1.0.0"

I also have some network call implementation and I don't want to use OkHttpClient from my-network-library. So I've created a module in the app to get my own instance of OkHttpClient.

@Module
@InstallIn(ApplicationComponent::class)
object NetworkModule {

    @Singleton
    @Provides
    fun provideOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            // CUSTOM CONFIG GOES HERE 
            .build()
    }
}

Now am getting below error.

error: [Dagger/DuplicateBindings] okhttp3.OkHttpClient is bound multiple times:

I know it's because of the @Provides declared in the my-network-library, but I didn't specify includes to the @Module annotation to inherit dependency from BaseNetworkModule. The issue may be fixed using @Qualifier annotation, but IMO, that'd be a workaround.

so my question is

  • Why dependency from a library module comes into the app module without using includes of @Module?
  • How to tell Hilt "Do not look for @Provides in external libraries (gradle dependencies) ?" unless I mark the module with @Module(includes = XXXModule)
like image 684
theapache64 Avatar asked Sep 11 '25 03:09

theapache64


1 Answers

Why dependency from a library module comes into the app module without using includes of @Module?

Because Hilt was designed to be as simple as possible for a regular android dev.

Hilt is a simple dude: he sees @Module @InstallIn in the compiled code, he uses it. Think of @InstallIn as the include in the regular Dagger2. Just placed in a different spot.


How to tell Hilt "Do not look for @Provides in external libraries (gradle dependencies) ?" unless I mark the module with @Module(includes = XXXModule)

Not possible. You'd have to not mark it with @Module @InstallIn(...).

In general I'm having troubles understanding why you would want that. How are you using Hilt features in my-network-library? Is it a shared module between different apps? And you want to include the module in some of those apps but not all of them?

like image 142
Bartek Lipinski Avatar answered Sep 12 '25 16:09

Bartek Lipinski