Dagger 2 injecting multiple instances of same object type

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

提交回复
热议问题