Im learning and newer to Dagger2 and stuck in the issue where I need to use both @Provides and @Binds in a Module. but its giving error
[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()
before I was using @Provides it worked fine but with combination I get above issue.
Component
@Component(modules = CarModule.class)
public interface CarComponent{
//constructor injection
Car getCar();
}
Module
@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);
}
}
Activity
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();
}
}
@Binds
is usually for the case when you have some inherited class and its interface and you want dagger to know this and be able to inject the interface. Usually you'd have
@Binds
abstract Engine bindsEngine(DieselEngine dieselEngine);
and then you can just inject engine without knowing the implementation detail (it's diesel engine).
In your case, if you remove both @Binds
methods, it should start working (if there's no other issue).
You are using @Binds
in the wrong way. Please read their documentation.
A @Binds method:
Must have a single parameter whose type is assignable to the return type. The return type declares the bound type (just as it would for a @Provides method) and the parameter is the type to which it is bound.
You have to change @Binds to @Provides.
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.