我的情况是需要两个Retrofit服务,每个服务都有业务实现。
@Provides
@Singleton
@Named("defaultMulhimService")
MulhimService provideMulhimService() {
return MulhimService.Creator.newMulhimService();
}
@Provides
@Singleton
@Named("MulhimServiceWithCache")
MulhimService providesMulhimServiceWithCache(){
return MulhimService.Creator.newMulhimServiceWithCache(mApplication);
}
我已经看过这个answer建议使用@Named注释来区分模块中的多个实例,但是我不知道如何注入它们。
答案 0 :(得分:1)
你可以使用这样的东西(https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2) -
@Provides @Named("cached")
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient client = new OkHttpClient();
client.setCache(cache);
return client;
}
@Provides @Named("non_cached") @Singleton
OkHttpClient provideOkHttpClient() {
OkHttpClient client = new OkHttpClient();
return client;
}
@Inject @Named("cached") OkHttpClient client;
@Inject @Named("non_cached") OkHttpClient client2;
基本上,您使用@Named限定符
注入实例