匕首2 - 为什么这是一个依赖循环?

时间:2015-09-23 16:03:29

标签: android dependency-injection dagger dagger-2

我正在尝试将应用程序的Context注入其他两个对象,AuthManagerApiClient

它们都取决于所述上下文,而ApiClient取决于AuthManager。为什么这是一个依赖循环,如果Context没有引用其他2?这可以解决吗?

编辑:这里有一些代码

@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();
}

2 个答案:

答案 0 :(得分:58)

@Provides @Singleton
public AuthManager providesAuthManager(AuthManager manager) {
    return manager;
}

提供providesAuthManager的{​​{1}}方法取决于AuthManager

你的周期:)

答案 1 :(得分:2)

删除providesAuthManager方法并在AuthManager构造函数中添加@Inject