Internal dependency injection using Dagger2

瘦欲@ 提交于 2020-01-15 12:45:29

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/32146077/internal-dependency-injection-using-dagger2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!