0

I am using MVP pattern to develop a Windows Form using c#.

I have a presenter MainPresenter which has reference of InfoPresenter so MainPresenter can access InfoPresenter's methods.

Now I want to access MainPresenter's methods in InfoPresenter. If I give reference of MainPresenter into InfoPresenter the application will break with following error.

System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'

Following is the code that is breaking:

MainPresenter

class MainPresenter : IMainPresenter
{
    private IInfoPresenter _infoPresenter;

    public MainPresenter(IInfoPresenter infoPresenter)
    {
        _infoPresenter = infoPresenter;
    }
}

InfoPresenter

class InfoPresenter : IInfoPresenter
{
    private IMainPresenter _mainPresenter;

    public InfoPresenter(IMainPresenter mainPresenter)
    {
        _mainPresenter = mainPresenter;
    }
}

If I remove the reference of MainPresenter from second class (InfoPresenter) it will work fine, but then I want to access some of its (MainPresenter) method into InfoPresenter and vice versa.

Twix
  • 392
  • 1
  • 12
  • 38
  • What do you mean by "the application will break"? What do you see exactly? A compilation error? If so, what is it? – o_weisman Jun 20 '19 at 08:24
  • @o_weisman `System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'` getting this error when I run code. – Twix Jun 20 '19 at 08:26
  • You're probably stuck in an endless creation loop. We need to see your Presenter classes creation code. How do you construct these instances? – o_weisman Jun 20 '19 at 08:28
  • yes exactly. Not getting you what you need? These are the presenter classes and I am instantiating other presenter in constructor. – Twix Jun 20 '19 at 08:31
  • How can you even write code that creates these classes? One of them has to have a constructor that doesn't require the other one or else it's not even writable (I'd love to see how you managed to create them). Make one of the constructors empty and use a different method like setPresenter(IMainPresenter parent) to set its parent after creation. – o_weisman Jun 20 '19 at 08:37
  • 1
    Try to put common methods in different class and access it in these both classes OR keep it in one class and call it in another. Both way dependency injection might cause stackoverflow. – Brij Jun 20 '19 at 08:49

0 Answers0