在Android Dagger中从依赖模块注入对象

时间:2017-03-16 08:59:25

标签: android dagger

我有两个模块,AppModuleSplashViewModule

AppModule

@Module
public final class AppModule {
    @NonNull
    private final MyApplication mApp;

    public AppModule(@NonNull MyApplication app) {
        mApp = app;
    }

    @Provides
    public Context provideAppContext() {
        return mApp;
    }

    @Provides
    public MyApplication provideApp() {
        return mApp;
    }

    @Singleton
    @Provides
    public UserManager provideUserManager() {
        return new UserManager();
    }
}

SplashviewModule

@Module
public final class SplashViewModule {

    @Inject
    UserManager mUserManager;

    @Provides
    public SplashInteractor provideInteractor() {
        return new SplashInteractorImpl(mUserManager);
    }

    @Provides
    public PresenterFactory<SplashPresenter> providePresenterFactory(@NonNull final SplashInteractor interactor) {
        return new PresenterFactory<SplashPresenter>() {
            @NonNull
            @Override
            public SplashPresenter create() {
                return new SplashPresenterImpl(interactor);
            }
        };
    }
}

我将这些注入到我的活动中:

@Override
protected void setupComponent(@NonNull AppComponent parentComponent) {
    DaggerSplashViewComponent.builder()
            .appComponent(parentComponent)
            .splashViewModule(new SplashViewModule())
            .build()
            .inject(this);
}

但这不起作用。 UserManager将为null。如何获取由UserManager创建的AppModule的单例实例并将其注入SplashViewModule

1 个答案:

答案 0 :(得分:1)

您无需在UserManager mUserManager;中声明SplashViewModule。只需为方法UserManager添加provideInteractor参数。

@Provides
public SplashInteractor provideInteractor(UserManager userManager) {
    return new SplashInteractorImpl(userManager);
}