views:

208

answers:

3

I'm currently trying out some MVP patterns sample and I have been told not create concrete Presenter objects in the View. Is there any way to have Presenter objects created dynamically ?

public partial class View: Window, IView
{
   private Presenter _presenter;

    public View()
    {
        InitializeComponent();
        _presenter = new Presenter(this); //Asked to avoid this
    }
}
+2  A: 

You're thinking it wrong. You don't create the presenter in the view. You create it elsewhere (application startup, other presenters) and it passes itself to the view, either as a constructor parameter, or by setting a property.

Like this:

class FooView : IFooView
{
    private readonly IFooPresenter presenter;

    public FooView(IFooPresenter presenter)
    {
        this.presenter = presenter;
    }
}

class FooPresenter1 : IFooPresenter
{
    private readonly IFooView view;

    public FooPresenter1()
    {
        view = new FooView(this);
    }
}
// or
class FooPresenter2 : IFooPresenter
{
    private readonly IFooView view;

    public FooPresenter2(IFooView view)
    {
        this.view = view;
        view.Presenter = this;
    }
}

And by the way, you seem to be using WPF. If that's the case you may want to have a look at the Model-View-ViewModel pattern instead.

Martinho Fernandes
This would not work in webforms. View is the first one that handles the request so it has to create a presenter.
epitka
@epitka: I hate webforms. Still a valid point though. I just assumed he was doing some desktop stuff since his View inherits from Window.
Martinho Fernandes
+2  A: 

With view first creation you can use an IoC container to create your Presenter:

public View(IMyPresenter presenter)
{
    InitializeComponent();
    _presenter = presenter;
}

Alternatively, you can use model (presenter) first where the View is passed to the Presenter in much the same way. See Which came first, the View or the Model? for discussion on this topic.

Or you could use a third object to bind the View and Presenter together, like the IBinder service in Caliburn.

GraemeF
A: 

If you are using webforms I do it in the constructor of the page or user control. Something like this using StructureMap

public UserProfileEdit()
        {
            _presenter = ObjectFactory.With<IUserProfileEdit>(this).GetInstance<UserProfileEditPresenter>();
        }
epitka