Dagger 2 injecting multiple instances of same object type

后端 未结 2 1493
失恋的感觉
失恋的感觉 2021-01-03 23:37

Background

I am converting my app to MVP architecture and found Dagger 2 to be useful to inject dependencies when needed. My app needs to communicat

2条回答
  •  感动是毒
    2021-01-03 23:47

    You are already halfway through the solution. To complete the solution try to do the following:

    @Provides
    @Named("myApiRestAdapter")
    RestAdapter provideMyRestAdapter(@Named("myApiGson") Gson gson, OkHttpClient okHttpClient) {
       return new RestAdapter.Builder()
                .setEndpoint(MY_API_URL)
                .setConverter(new GsonConverter(gson))
                .setClient(new OkClient(okHttpClient))
                .build();
    }
    
    @Provides
    @Named("thirdPartyApiRestAdapter")
    RestAdapter provideThirdPartyRestAdapter(@Named("thirdPartyApiGson") Gson gson, OkHttpClient okHttpClient) {
       return new RestAdapter.Builder()
                .setEndpoint(THIRD_PARTY_API_URL)
                .setConverter(new GsonConverter(gson))
                .setClient(new OkClient(okHttpClient))
                .build();
    }
    

    To make sure that only two instances of your RestAdapters are created during the lifetime of the application, annotate both the methods providing RestAdapter with @Singleton like you have done with your other methods. As for your other question whether Dagger 2 will create new instance of RestAdapter every time it has to inject it, I think it does this exactly, but I'm not sure on this.

    Hope this helps!

提交回复
热议问题