我有几个相互依赖的课程,GamePresenter
和GameManager
。
我正在尝试使用构造函数注入注入它们,但我仍然无法弄清楚如何使其工作,因为我发现了一个依赖循环错误。
GameFragment
应该将GamePresenter
注入到片段中,因此第一个会与第二个对话,而GameManager
会被注入GamePresenter
。
GamePresenter
是:
@Inject
GamePresenter(GameRepository gameRepository, GameManager gameManager, GameContract.View view) {
DaggerGameManagerComponent.builder()
.gameManagerModule(new GameManagerModule(this))
.build()
.inject(this);
this.view = view;
this.gameRepository = gameRepository;
this.gameManager = gameManager;
}
GamePresenterModule
是:
@Module
public class GamePresenterModule {
private final GameContract.View view;
public GamePresenterModule(GameContract.View view) {
this.view = view;
}
@Provides
GameContract.View provideGameContractView() {
return view;
}
}
GamePresenterComponent
是:
@FragmentScoped
@Component(dependencies = RepositoryComponent.class, modules = GamePresenterModule.class)
public interface GamePresenterComponent {
void inject(GameFragment gameFragment);
}
GameManager
是:
@Inject
public GameManager(GamePresenter gamePresenter, Game game) {
this.gamePresenter = gamePresenter;
this.game = game;
}
GameManagerModule
是:
@Module
public class GameManagerModule {
private GamePresenter presenter;
public GameManagerModule(GamePresenter presenter) {
this.presenter = presenter;
}
@Provides
GameManager provideGameManager(Game game) {
return new GameManager(this.presenter, game);
}
@Provides
Game provideGame() {
return new Game();
}
}
GameManagerComponent
是:
@FragmentScoped
@Component(dependencies = GamePresenterComponent.class, modules = GameManagerModule.class)
public interface GameManagerComponent {
void inject(GamePresenter gamePresenter);
}
最后,GameFragment
是:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
DaggerGamePresenterComponent.builder()
.repositoryComponent(((GameApplication) getActivity().getApplication()).getRepositoryComponent())
.gamePresenterModule(new GamePresenterModule(this))
.build()
.inject(this);
}
提前多多感谢!
答案 0 :(得分:0)
当你遇到这类问题时,你应该过度思考你的架构。
在这种情况下,我建议不要将GameManager
注入GamePresenter
。而是使用GameManager
中所需的任何方法定义接口,让GameManager
实现它并在构造函数或提供者中注册它。