dors dors - 12 days ago 4
Android Question

Internal dependency injection using Dagger2

I want to use Dagger2.

Say I have the following dependencies:


  • Class A depends on class B

  • Class B depends on class C



I tried to create a Module that provides B and C, and a Component that provides A, however only B is injected into A, and the reference to C in B remains null.

What is the classes structure I need to implement using dagger?

Answer

You can either use constructor injection or field injection; and either constructor-inject or module-inject.

Constructor-@Inject might be buggy, because I've been using Modules and Components since the dawn of time.

@Singleton
public class A {
    B b;

    @Inject
    public A(B b) {
        this.b = b;
    }
}

@Singleton
public class B {
    C c;

    @Inject
    public B(C c) {
        this.c = c;
    }
}

@Singleton
public class C {
    @Inject
    public C() {
    }
}

@Singleton
@Component
public interface SingletonComponent {
    void inject(MainActivity mainActivity);
}

Or

public class A {
    private B b;

    public A(B b) {
        this.b = b;
    }
}

public class B {
    private C c;

    public B(C c) {
        this.c = c;
    }
}

public class C {
}

@Module
public class ProviderModule {
    @Provides
    @Singleton
    public A a(B b) {
        return new A(b);
    }

    @Provides
    @Singleton
    public B b(C c) {
        return new B(c);
    }

    @Provides
    @Singleton
    public C c() {
        return new C();
    }
}

@Component(modules={ProviderModule.class})
@Singleton
public interface SingletonComponent {
    A a();
    B b();
    C c();

    void inject(MainActivity mainActivity);
}

or with field injection

@Singleton
public class A {
    @Inject
    B b;

    @Inject    
    public A() {
    }
}

@Singleton
public class B {
    @Inject
    C c;

    public B() {
    }
}

@Singleton
public class C {
    @Inject
    public C() {
    }
}

@Component
@Singleton
public interface SingletonComponent {
    A a();
    B b();
    C c();

    void inject(MainActivity mainActivity);
}