2017-04-01 167 views
0

我有幾個相互依賴的類,GamePresenterGameManager。 我試圖注入它們使用構造函數注入,但我仍然無法弄清楚如何使它的工作,因爲我得到了依賴性循環錯誤。匕首2個模塊相互依賴

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

當您遇到此類問題時,您應該過度考慮您的架構。

在這種情況下,我建議不要將GameManager注入GamePresenter。相反,使用GameManager所需的任何方法定義接口,讓GameManager實現它並在構造函數或提供程序中註冊它。

+0

我該怎麼做?特別是「將其註冊到構造函數或提供者中」 – noloman