简体   繁体   中英

Dagger 2 - Why is this a dependency cycle?

I'm trying to inject the application's Context into 2 other objects, an AuthManager and an ApiClient .

Both of them depends on said context, and the ApiClient depends on the AuthManager . Why is this a dependency cycle, if Context 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();
}
@Provides @Singleton
public AuthManager providesAuthManager(AuthManager manager) {
    return manager;
}

Your providesAuthManager method which provides an AuthManager depends on an AuthManager .

There's your cycle :)

取出providesAuthManager方法并添加@Inject在AuthManager构造函数。

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