Dagger 2模块相互依赖

时间:2017-04-01 18:23:36

标签: android dependency-injection dagger-2

我有几个相互依赖的课程,GamePresenterGameManager。 我正在尝试使用构造函数注入注入它们,但我仍然无法弄清楚如何使其工作,因为我发现了一个依赖循环错误。

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

提前多多感谢!

1 个答案:

答案 0 :(得分:0)

当你遇到这类问题时,你应该过度思考你的架构。

在这种情况下,我建议不要将GameManager注入GamePresenter。而是使用GameManager中所需的任何方法定义接口,让GameManager实现它并在构造函数或提供者中注册它。