How to prevent Hilt from picking dependency from a library?

a 夏天 提交于 2020-08-09 08:17:06

问题


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)

回答1:


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?



来源:https://stackoverflow.com/questions/63276876/how-to-prevent-hilt-from-picking-dependency-from-a-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!