Dagger 2 injecting multiple instances of same object type

后端 未结 2 1472
失恋的感觉
失恋的感觉 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!

    0 讨论(0)
  • 2021-01-04 00:03

    I saw this thread after posting my answer to a similar question. I wanted to provide a link because I think the same approach could be useful depending on your situation. It may be overkill for this exact question but I wanted to share in case it helps someone else.

    https://stackoverflow.com/a/52348744/5046784

    In short you can create unique interfaces / classes for each named object(e.g. MyApiGson and ThirdPartyApiGson) and then create @Provides for those rather than the generic Gson class. This way you can inject the instances by class/interface rather than a magic string name that you need to lookup or remember. Its a little more work but it helps when you have a bunch of independent modules that provide difference instances of the same Class.

    0 讨论(0)
提交回复
热议问题