简体   繁体   中英

Dagger2 How to make Injected Object know who created it

For example I have:

Public Class A extends Parent{
    @Inject B b;

    public A(){
     DaggerAppComponent.create().inject(this); //inject b here
    }

    public void doStuff(){
        b.start();
    }

    @Override
    public void onDone(){
       Log.v(TAG, "done");
    }
}

and in class B:

Public Class B{
    private Parent parent;

    Public B(Parent parent){
        this.parent = parent;
    }

    public void start(){
       parent.onDone();
    }
}

My question is how can I pass the instance of class A to class B? In the dagger AppModule I have provide methods for both class A and class B:

@Module
Public AppModule{

    @Provide
    @Singleton
    A provideA(){
        return new A();
    }

    @Provide
    B provideB(A a){
        return new B(A a);
    }

}

With this code I get a circular dependency, resulting in a stack overflow error. When A is created, A tries to inject B, and a new A is created when the provide method creates B...

What's the correct way of injecting this? Or should I avoid injection in this case?

New Thoughts: Maybe I can save the created objected(a and b) in the dagger module, and when the provide method is called, return the saved instance instead of creating a new one. This should be the same as using @Singleton, but it appears to me that the constructor is still called when the provide method is called.(When the constructor of A is called, it creates the stack overflow problem.) And I'm also worrying that saving variables in dagger module is a bad practice.

Found this "core principle of dependency injection: a class shouldn't know anything about how it is injected." at https://google.github.io/dagger/android.html

Unless someone come up and tell me I'm wrong, I'm going to assume that the injected object shouldn't know its parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM