简体   繁体   中英

Dagger2 where inject @Named @Provides in dependent module?

I use dagger2 demo by https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2 . I want to use cached and non_cached retrofit call. I create in NetModule.java

@Provides @Named("cached")
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .build();
    return okHttpClient;
}

@Provides @Named("non_cached")
@Singleton
OkHttpClient provideOkHttpClientNonCached() {
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .build();
    return okHttpClient;
}

GitHubModule.java is dependent on NetModule.java. my GitHubComponent.java

@UserScope
@Component(dependencies = NetComponent.class, modules = GitHubModule.class)
public interface GitHubComponent {
void inject(DemoDaggerActivity activity);
}

my NetComponent.java

@Singleton
@Component(modules={ApplicationModule.class, NetModule.class})
public interface NetComponent {
// downstream components need these exposed
Retrofit retrofit();
OkHttpClient okHttpClient();
SharedPreferences sharedPreferences();
}

In my DemoDaggerActivity.java I inject retrofit:

@Inject @Named("cached")
OkHttpClient mOkHttpClient;

@Inject
Retrofit mRetrofit;

After rebuild project I get error:

在此输入图像描述

Where can I tell to dagger, that i want to use cached or non_cached retrofit?

Your Retrofit provider should use @Named annotation for OkHttpClient, for example:

@Provides
@Singleton
public Retrofit provideRetrofit(@Named("cached") OkHttpClient okHttpClient)
{
    return new Retrofit.Builder()
            .baseUrl("...")
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();
}

You have two methods with same name: provideOkHttpClient() . Rename one of them, make them distinct.

If you are using kotlin, the correct way to inject named is next:

@field:[Inject Named("api1")] .

Source: https://medium.com/@WindRider/correct-usage-of-dagger-2-named-annotation-in-kotlin-8ab17ced6928

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM