I spend several hours for searching but I still don't find any clearly example about Constructor Injection with Dagger 2.
Assume I have below declaration, how can I create an instance of class B somewhere using Dagger 2 injection?
@Module
public class ClassA {
@Provides public ClassA provideA(){
return new ClassA();
}
}
public class ClassB{
private ClassA a;
@Inject public ClassB(ClassA a){
this.a = a;
}
}
If you have
@Module
public class ModuleA {
/*unscoped*/ @Provides public ClassA provideA(){
return new ClassA();
}
}
/*unscoped*/
public class ClassB{
private ClassA a;
@Inject public ClassB(ClassA a){
this.a = a;
}
}
Then you'll need
/*unscoped*/
@Component(modules={ModuleA.class})
public interface MyComponent {
ClassA classA();
ClassB classB();
}
And then you can either access like so
MyComponent component = DaggerMyComponent.create();
ClassB classB = component.classB();
Or
/*unscoped*/
@Component(modules={ModuleA.class})
public interface MyComponent {
ClassA classA();
ClassB classB();
void inject(MyClass myClass);
}
And
public class MyClass {
@Inject
ClassB classB;
public void init() {
MyComponent component = getComponent();
component.inject(this);
}
}