I am experimenting with the 'new' Android support in Dagger 2.
I want to set up the following architecture in Dagger:
Application => Activity => Controller (Conductor)
(Controller is basically a View
that gets instantiated by the system. You can think of it like Fragment
s but without Dagger Injection support)
For each level I have defined a dependency: ApplicationDep
, ActivityDep
and ControllerDep
.
- My
Controller
should be able to inject all of these dependencies. - My
Activity
should be able to inject theApplicationDep
and theActivityDep
- My
Application
should only be able to inject theApplicationDep
Everything works except in my Controller
.
I am unable to inject the ActivityDep
.
public class MyController extends Controller {
@Inject
ApplicationDependency applicationDependency;
//@Inject
//ActivityDependency activityDependency; // can not be provided
@Inject
ControllerDependency controllerDependency;
@NonNull @Override protected View onCreateView(@NonNull LayoutInflater layoutInflater, @NonNull ViewGroup viewGroup) {
ConductorInjection.inject(this);
return layoutInflater.inflate(R.layout.controller_main, viewGroup, false);
}
}
Currently I have my ControllerBindingModule
bound on my ApplicationComponent
, however this should be bound on the Activity
in order for it to be also available in the Controller
.
How can I do this?
@Singleton
@Component(modules = {
ApplicationModule.class,
ActivityBindingModule.class,
AndroidSupportInjectionModule.class,
ConductorInjectionModule.class,
ControllerBindingModule.class
})
interface AppComponent extends AndroidInjector<App> {
@Component.Builder
abstract class Builder extends AndroidInjector.Builder<App> {}
}
The full code can be found on Github.
Thanks.
It sounds like controller is a subcomponent of activity component.
I took a look at your GitHub, so I change some of your code to answer.
First, for the
Activity
injection.Controller
is not subcomponent ofAppcomponent
, so it only needActivityBindingModule
.AppComponent.java
For the same reason, we only need to implement
HasActivityInjector
inApp
.App.java
Because I need to declare
Controller
as subcomponent ofActivityComponent
, I use step 2 & step 3 in Dagger documentation about injecting activity objectsChange your
ActivityBindingModule
ActivityBindingModule.java
Create an
ActivityComponent
.MainActivityComponent.java
Next, it time to set controller as a subcomponent of activitycomponent.
Add
ControllerBindingModule.class
toMainActivityComponent
.And implement
HasControllerInjector
inMainActivity
.MainActivity.java
No need to change other files, and what you want is done.