How to resolve a circular dependency while still using Dagger2?

后端 未结 3 1482
猫巷女王i
猫巷女王i 2021-02-12 15:29

I have two classes, Foo and Bar, which depend on each other, as well as various other classes. I am using Dagger-2 for dependency injection, b

3条回答
  •  太阳男子
    2021-02-12 16:05

    This is how I resolved it, without parent classes.

    Class 1: Engine. (in component interface)

    @Provides
    public Engine myEngine(Context context) {
        return new Engine (context);
    }
    

    Class 2: Parts. Engine also needs Parts instance but the creation is delayed.

    @Inject
    public Parts(Context context, Engine engine) {
        this.context = context;
        this.engine= engine;
        engine.setParts(this);
    }
    

    Circular dependency can be achieved but one class must be initiated first before the other.

    Again, if possible, refactor code to avoid circular DI.

提交回复
热议问题