【发布时间】:2021-03-08 03:47:05
【问题描述】:
我正在学习和更新 Dagger2,并且遇到了我需要在模块中同时使用 @Provides 和 @Binds 的问题。但它给出错误
[Dagger/DependencyCycle] Found a dependency cycle:
public interface CarComponent{
^
com.stupido.daggertutorial.Engine is injected at
com.stupido.daggertutorial.CarModule.bindsEngine(arg0)
com.stupido.daggertutorial.Engine is injected at
com.stupido.daggertutorial.CarModule.providesCar(engine, …)
com.stupido.daggertutorial.Car is requested at
com.stupido.daggertutorial.CarComponent.getCar()
在我使用 @Provides 之前它工作得很好,但结合起来我得到了上述问题。
组件
@Component(modules = CarModule.class)
public interface CarComponent{
//constructor injection
Car getCar();
}
模块
@Module
public abstract class CarModule {
@Binds
abstract Wheels bindsWheels(Wheels wheels);
@Binds
abstract Engine bindsEngine(Engine engine);
@Provides
static Car providesCar(Engine engine,Wheels wheels){
return new Car(wheels,engine);
}
}
活动
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CarComponent carComponent = DaggerCarComponent.create();
Car car = carComponent.getCar();
}
}
【问题讨论】: