如何将 Activity 注入到正在注入 Activity 的对象?

How inject the Activity to object that is being injected to the Activity?

我有这个模块:

@Module
public class UserProfileModule {

    @Provides
    @Singleton
    UserProfileController providesUserProfileController() {
        return new UserProfileController();
    }

}

和这个组件:

@Component(modules = {UserProfileModule.class})
@Singleton
public interface AppComponent {

    void inject(UserProfileActivity activity);

}

到目前为止,在我的 UserProfileActivity 中我可以 @Inject 一个 UserProfileController。但是现在,我需要将 UserProfileActivity 注入控制器。我的意思是,互相注入。

我可以通过在 UserProfileActivity 中调用 UserProfileController setter 来完成:setActivity(this);,但如果可以自动进行就更好了。

如何实现?

谢谢。

对于初学者:将其添加到构造函数中。然后声明依赖关系。

@Provides
@Singleton
UserProfileController providesUserProfileController(UserProfileActivity activity) {
    return new UserProfileController(activity);
}

这样做之后,匕首会抱怨无法提供 UserProfileActivity,除非你已经这样做了。如果不这样做,请添加另一个模块,或者只提供来自同一模块的依赖项。实际实现如下,首先我们需要修复你的代码。

@Singleton 是对层次结构 top 的依赖。你不能——或者至少不应该——对 @Singleton 注释对象有 activity 依赖性,因为这可能会导致难闻的气味 and/or 内存泄漏。引入自定义范围 @PerActivity 以用于活动生命周期内的依赖项。

@Scope
@Retention(RUNTIME)
public @interface PerActivity {}

这将允许对象的正确范围。 另请参考一些关于 dagger 的教程,因为这是一个非常重要的问题,并且在一个答案中涵盖所有内容会太多。例如Tasting dagger 2 on android

以下通过扩展您的模块使用上述 2 个选项的后一种方法:

@Module
public class UserProfileModule {

    private final UserProfileActivity mActivity;

    public UserProfileModule(UserProfileActivity activity) {
        mActivity = activity;
    }

    @Provides
    @PerActivity
    UserProfileActivity provideActivity() {
        return mActivity;
    }

    @Provides // as before
    @PerActivity
    UserProfileController providesUserProfileController(UserProfileActivity  activity) {
        return new UserProfileController(activity);
    }

}

如果您现在使用组件 Builder,则可以使用 activity 作为参数创建模块的新实例。然后将正确提供依赖项。