使用 Dagger 2 在 @Provides 方法中注入依赖项

Injecting dependencies inside @Provides methods with Dagger 2

我使用 Dagger 2 正确创建了这三个依赖项(我通过调试验证它们确实存在),我们称它们为 a, b, c,如下所示:

class Example {
    ...
    @Inject A a;
    @Inject B b;
    @Inject C c;
    ...
},

SomeModule提供如下:

@Module
class SomeModule {
    ...
    @Singleton @Provides A provideA(){return new A()};
    @Singleton @Provides B provideB(){return new B()};
    @Singleton @Provides C provideC(){return new C()};
    ...
},

并且该组件相当简单:

@Component(modules = {SomeModule.class, ...})
class SomeComponent {
    ...
    void inject(Example example);
    ...
},

我需要它们来创建另一个对象,我们称它们为 d, e,像这样:

public Example(){
    DaggerSomeComponent.builder().build().inject(this);
    ...
    this.d = new D(c);
    this.e = new E(d, a, b);
    ...
}

我的问题是:是否有可能达到这样的目的?

class Example {
    ...
    @Inject A a;
    @Inject B b;
    @Inject C c;
    @Inject D d;
    @Inject E e;
    ...
    public Example(){
        DaggerSomeComponent.builder().build().inject(this);
        ...
    }
}

是的,@Provides methods can take parameters。 Dagger 将在调用该方法之前创建实例。

@Provides D provideD(C c){return new D(c)};
@Provides E provideE(A a, B b, D d){return new E(d, a, b)};