C++ Model View Presenter: Where to construct presenter

dependency-injectionmvppresentation-model

I'm using the Model View Presenter (MVP) pattern as described in The Humble Dialog Box paper (pdf) with an MFC project. I'm sure the issue is the same with most GUI toolkits.

The thing that's bothering me is the concrete view (i.e., the dialog class) is creating not only the presenter but also the services that the presenter needs. Is that normal? Why does the view need to know what services the presenter needs? What I'm thinking is that I should dependency inject the presenter into the dialog class.

The main control for the application is a class derived from CWinApp. So should I construct services and presenter in this class and then inject them into the dialog class?

Although how would I dependency inject the presenter into the dialog class when the presenter needs a reference to the view class in it's constructor?

MyPresenter(IView *view, MyService *service);

Also how about if the main window spawns off a popup window, where should the details for that windows presenter and services get constructed?

Since this is C++ I don't think I'd be interested in any kind of DI framework.

UPDATE

One idea I had was to construct the presenter with a null view, constructor inject the presenter into the dialog class, and then in the constructor of the dialog class call a SetView(IView *view) method on the presenter with this where this would be the dialog class (which derives from IView). So:

MyApp::Start()
{
  SomeService *service = new SomeService();
  MyPresenter *presenter = new MyPresenter(null, service);
  MyDialog *dialog = new MyDialog(presenter);
  ...
}

MyDialog::MyDialog(MyPresenter *presenter):
 presenter_(presenter)
{
  presenter_->SetView(this);
}

Seems a little kludgy but keeps service construction out of the Dialog class. The null view seems a little dangerous. An alternative would be to actually construct a NullView class that had empty method bodies and then pass that into the presenter constructor.

Best Answer

Perhaps a better solution is to use a factory class or method that knows how to build a presenter? The view would pass itself to the factory method and store the return value in it's presenter member.

This decouples information about how a presenter is constructed (dependencies on services or whatever) from the view itself.