Dagger 2 - Why is this a dependency cycle?
22,544
Solution 1
@Provides @Singleton
public AuthManager providesAuthManager(AuthManager manager) {
return manager;
}
Your providesAuthManager
method which provides an AuthManager
depends on an AuthManager
.
There's your cycle :)
Solution 2
Remove the providesAuthManager
method and add @Inject
in your AuthManager Constructor.
Author by
Christopher Francisco
Updated on January 01, 2020Comments
-
Christopher Francisco over 4 years
I'm trying to inject the application's
Context
into 2 other objects, anAuthManager
and anApiClient
.Both of them depends on said context, and the
ApiClient
depends on theAuthManager
. Why is this a dependency cycle, ifContext
doesn't have a reference to the others 2? can this be solved?EDIT: here is some code
@Module public class AppModule { private final Application application; public AppModule(Application application) { this.application = application; } @Provides @Singleton Context provideApplicationContext() { return this.application; } } @Module public class NetworkModule { @Provides @Singleton public AuthManager providesAuthManager(AuthManager manager) { return manager; } @Provides @Singleton public ApiClient providesApiClient(ApiClientFactory factory) { return factory.create(); } } @Singleton @Component(modules = {AppModule.class, NetworkModule.class}) public interface ApplicationComponent { void inject(BaseActivity activity); // Exported for child-components Context context(); ApiClient apiClient(); AuthManager authManager(); }
-
nhaarman over 8 yearsIt helps to add any error messages you get to the question. In this case, you've interpreted the error message the wrong way, making it harder for us to help :)
-
Christopher Francisco over 8 yearsI see. It seems I misunderstood the coffee maker example, as I thougt by placing the
AuthManager
as a local param, dagger would auto-inject to it. Seems like the right way is to set theContext
as the local param. Thanks :) -
user3265561 almost 8 yearsThis answer prompted me to double check a provides method and saved me hours of effort tracking down something caused by a simple typo. Thanks!
-
nhoxbypass over 6 yearsThis lead to other error: "...cannot be provided without @Provide annotated-method"
-
Derek Zhu about 6 yearsI think what you are looking for is @Bind