【问题标题】:Dagger 2 method injection?匕首2方法注入?
【发布时间】:2018-06-27 11:58:49
【问题描述】:

我有 2 个类,我希望对其进行依赖注入。基本上两者都需要彼此的对象来执行某些任务。

头等舱

public class AppMobilePresenter {
AppPresenter appPresenter;

@Inject
public AppMobilePresenter(AppPresenter appPresenter) {
    this.appPresenter = appCMSPresenter;
}
}

它的模块

@Module
public class AppMobilePresenterModule {
@Provides
@Singleton
public AppMobilePresenter providesAppMobilePresenter(AppPresenter appPresenter) {
    return new AppMobilePresenter(appPresenter);
}
}

二等

public class AppPresenter {
AppMobilePresenter appMobilePresenter;

@Inject
public AppPresenter() {
}

@Inject 
void setAppMobilePresenter(AppMobilePresenter appMobilePresenter){
    this.appMobilePresenter=appMobilePresenter;
}
}

它的模块

@Module(includes = { AppMobilePresenterModule.class})
public class AppPresenterModule {
@Provides
@Singleton
public AppPresenter providesAppPresenter() {
    return new AppPresenter();
}
}

我对两者都有一个共同的组件

@Singleton
@Component(modules = {AppPresenterModule.class})
public interface AppPresenterComponent {
AppPresenter appPresenter();
}

从我的应用程序类构建组件并运行应用程序后,我在 AppPresenter 类中获得了 AppMobilePresenter 对象 null。 方法注入是否还需要做其他事情。

【问题讨论】:

  • 我不认为,这种循环依赖是一个很好的解决方案。可能制作一个通用 Module ,这对于这两个类的初始化都是必需的。首先在 Application 类中创建该依赖项。为这两个提供相同的内容。
  • @Sreehari 我知道这不是一个好的解决方案,但根据我当前的代码库,这是我能得到的唯一解决方案。我必须在课堂上拥有彼此的对象。

标签: android dependency-injection dagger-2


【解决方案1】:

在调用构造函数时不会发生方法注入,就像在 @Provides 方法中所做的那样;如果你希望方法注入发生,Dagger 需要在其生成的代码中调用你的 @Inject 注释构造函数。

看起来您更喜欢构造函数注入,无论如何这更安全,但尝试方法注入只是为了避免依赖循环。不幸的是,这行不通。相反,切换回构造函数注入和use the technique shown here

@Singleton
public class AppMobilePresenter {
  AppPresenter appPresenter;

  @Inject
  public AppMobilePresenter(AppPresenter appPresenter) {
    this.appPresenter = appCMSPresenter;
  }
}

@Singleton
public class AppPresenter {
  Provider<AppMobilePresenter> appMobilePresenterProvider;

  @Inject
  public AppPresenter(Provider<AppMobilePresenter> appMobilePresenterProvider) {
    this.appMobilePresenterProvider = appMobilePresenterProvider;
  }
}

上面的代码可以使用相同的组件,并且不需要任何模块。需要注意的是,要从 AppPresenter 访问 AppMobilePresenter,您需要调用 appMobilePresenterProvider.get(),除了构造函数和 @Inject 方法之外,您可以在任何地方调用它。这样就解决了构造问题:Dagger 否则无法在不先创建 AppPresenter 的情况下创建 AppMobilePresenter,而在不先创建 AppMobilePresenter 的情况下无法创建 AppPresenter。不过,它可以创建一个 Provider,并在您稍后调用它时提供实例。

如果未来的读者真的需要字段或方法注入,他们可以不理会您的 @Inject 构造函数和方法,同时删除模块并切换到方法注入 Provider&lt;AppMobilePresenter&gt;,这是必要的,因为方法注入具有相同的构造顺序依赖循环关注的是构造函数注入。

【讨论】:

  • @Marcin(编辑):抱歉回滚,但我没有看到实质性的变化,而且看起来你的编辑破坏了我在我的免费 5- 中添加的一些注释分钟编辑窗口。如果编辑内容丰富且可能对未来的读者有所帮助,我愿意进行编辑。
  • Np。再次编辑。不过变化不大:)
  • @Marcin:啊。我不同意编辑首先是必要的,因为上下文使该短语明确无误。您只是根据自己的喜好更改了措辞,这似乎并不重要,而且似乎不太可能对未来的读者有所帮助。
  • 随意回滚
猜你喜欢
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
相关资源
最近更新 更多