Skip to content Skip to sidebar Skip to footer

Order Of Dependency Injection When Using Scopes

I'm currently trying to figure out Dagger 2. I am trying to set up 4 scopes: App, User, Activity, Fragment. User and Activity components are Subcomponents of App. Fragment is a Com

Solution 1:

To my best knowledge, Dagger-2 doesn't support "partial injections".

Therefore, when you call myComponent.inject(this), Dagger-2 throws an error if myComponent can't provide all @Inject annotated members of this.

I see two ways to work around this limitation:

  1. Remove @Inject annotation from UserProfile, expose UserProfile via public method in UserComponent and inject it manually when UserComponent is ready to be used. Something analogous to this: userProfile = userComponent.getUserProfile()
  2. Don't make UserComponent dependent on data fetching. UserComponent could be used to inject Toolbar and some UserProfileProvider at the same time, and you will fetch UserProfile from UserProfileProvider when it is available.

I personally think that second approach is the better choice. DI libraries should be used in order to satisfy objects' dependencies at construction time. In Android we can't construct Activity or Fragment ourselves, therefore we perform DI in onCreate(), onAttach(), onCreateView(), etc., but it does not mean that we should be using DI libraries in order to assist in controlling the flow of applications.


Solution 2:

Subcomponents work's similar to inheritance(extends), in your case User component and Activity component extending App component but there is no relation between User component and Activity component so when you request User dependency in Activity it will fail.

Subcomponent can't provide any dependency to other Subcomponent.

Instead, you can make Activity component as a subcomponent of User component. This will also give you the flexibility to switch user.


Post a Comment for "Order Of Dependency Injection When Using Scopes"