提供并注入两个具有不同实现的实例 - Dagger 2

时间:2017-01-11 22:08:47

标签: android dependency-injection dagger-2

我的情况是需要两个Retrofit服务,每个服务都有业务实现。

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

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

我已经看过这个answer建议使用@Named注释来区分模块中的多个实例,但是我不知道如何注入它们。

1 个答案:

答案 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限定符

注入实例