Android Dagger 2: Inject versus Provides

前端 未结 1 768
名媛妹妹
名媛妹妹 2020-12-31 01:43

I have a question regarding Android Dagger 2 und the usage of @Inject and @Provide annotations. Given are the following two simplified examples:

相关标签:
1条回答
  • 2020-12-31 02:09

    They work similarly, and the @Inject style is preferred when you have such an easy choice like in your example. However, this isn't always the case:

    • If B, which consumes A, is not under your control and not DI-aware, you will have no way to add the @Inject annotation.
    • If B is an interface, you will need @Provides (or @Binds in newer Dagger versions) to identify which implementation to use.
    • If you choose not to use your Dagger object graph for every injected parameter, you can call the constructor manually whether it is marked @Inject or not. This might be the case if you want a specific instance or constant as a constructor parameter, but you can't or don't want to set up the binding for the whole object graph.

    @Provides allows you to effectively create a factory method, with everything that allows. This is a great way to change which instances are included in your graph, or to effectively add to the class's constructor graph-wide if you can't (or shouldn't) change the class itself.

    • You can return an existing instance rather than a new one. Note that custom scopes (implemented in Dagger through subcomponents) might be a better fit for common cases, but if you have more complex instance control or use a third-party library that controls instances, you could put that into your factory method.
    • If you want your binding to return null sometimes that logic can live in a @Provides method. Make sure you annotate the injection sites as @Nullable.
    • You can choose between implementations with a factory method like a @Provides method, particularly if the choice depends on runtime environment.
    • You can run post-construction logic, including instance registration or initialization.
    0 讨论(0)
提交回复
热议问题