alapshin
alapshin

Reputation: 881

How to inject into the same class from different Dagger2 components?

Let's say I have multiple activities and every activity contains separate Dagger2 component. So FooActivity has FooComponent and BarActivity has BarComponent. Also I have some viewgroup let's say BazViewGroup that can be used in both activities and must receive some dependencies through dagger graph. What is best way to inject dependencies into instance of this viewgroup since we don't know in advance in what activity it belongs?

Right now I have the following setup:

  1. Every activity exposes method getComponent() which returns component contained in this activity
  2. Every component extends interface like

    public interface CanInjectIntoBazViewGroup {
        void inject(BazViewGroup viewgroup);
    }
    
  3. Inside BazViewGroup constuctor I get reference to activity get component from it, cast it to CanInjectIntoBazViewGroup and call inject method.

Is there is a better way to do this?

Upvotes: 2

Views: 299

Answers (1)

Vasiliy
Vasiliy

Reputation: 16278

The best practice for Dagger 2 is not to abuse it (like any other thing).

So, if you already have components for your Activities, and you have a reference to BazViewGroup in both Activities, then I don't see any reason to use Dagger 2 in order to perform DI into this BazViewGroup.

There are two cases.

ViewGroup is declared in XML:

If you declare BazViewGroup in XML and let Android inflate it for you, then you can perform a "method DI" - define methods like setXYZ() on this object and pass XYZ from your Activities after view hierarchy inflated.

You create the ViewGroup programmatically:

If you are instantiating the ViewGroup programmatically, then you can add its dependencies as constructor parameters.

Both approaches are not so clean because they create some coupling between Activity and internals of ViewGroup, but it is much better than coupling ViewGroup to Dagger framework.

The cleaner way is to remove these dependencies from ViewGroup. I guess you need them in order to perform some actions on user interaction, or to query for data, right? Why don't create callback interface and delegate all these actions to the enclosing Activity? This way, if you refactor your business logic one day, your custom Views won't be affected.

Upvotes: 1

Related Questions