2017-01-11 108 views
0

我有一種情況,我需要兩個Retrofit Services,每個都有其業務實現。提供並注入兩個不同實現的實例 - Dagger 2

@Provides 
    @Singleton 
    @Named("defaultMulhimService") 
    MulhimService provideMulhimService() { 
     return MulhimService.Creator.newMulhimService(); 
    } 

    @Provides 
    @Singleton 
    @Named("MulhimServiceWithCache") 
    MulhimService providesMulhimServiceWithCache(){ 
     return MulhimService.Creator.newMulhimServiceWithCache(mApplication); 
    } 

我已經看了這個answer使用@Named標註爲模塊,以不同的多個實例這表明,但我不知道,如何將它們注入。

回答

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預選賽

+0

是,對於構造函數注入太工程實例? –

+2

@MohamedIbrahim是的,只是註釋參數。 –

相關問題