Moh*_*him 1 android dependency-injection dagger-2
我有一种情况,我需要两个改造服务,每个服务都有其业务实现。
@Provides
@Singleton
@Named("defaultMulhimService")
MulhimService provideMulhimService() {
return MulhimService.Creator.newMulhimService();
}
@Provides
@Singleton
@Named("MulhimServiceWithCache")
MulhimService providesMulhimServiceWithCache(){
return MulhimService.Creator.newMulhimServiceWithCache(mApplication);
}
Run Code Online (Sandbox Code Playgroud)
我已经看过这个答案,它建议使用 @Named 注释来区分模块中的多个实例,但我不知道如何注入它们。
你可以使用这样的东西(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;
Run Code Online (Sandbox Code Playgroud)
基本上,您使用 @Named 限定符注入实例
| 归档时间: |
|
| 查看次数: |
1765 次 |
| 最近记录: |