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



我有一个情况,我需要两个改造服务,每个服务都有其业务实施。

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

我已经看过这个答案,它建议使用@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;

基本上,您使用@Named限定符注入实例

最新更新