Prism View Injection Presenter and Garbage Collection - wpf

In Microsoft's view injection sample/article they have the code like the following:
public void Initialize()
{
this.RegisterViewsAndServices();
EmployeesPresenter presenter = this.container.Resolve<EmployeesPresenter>();
IRegion mainRegion = this.regionManager.Regions[RegionNames.MainRegion];
mainRegion.Add(presenter.View);
}
http://msdn.microsoft.com/en-us/library/dd458920.aspx
here Presenter is resolved which contains the public property of type IEmployeesView and thats used for injecting the view to the region. The benefit of resolving the presenter is that it gets automatically tied to the view (by taking it in constructor (via unity)). However don't you think the Presenter is prone to garbage collection because nothing has reference to presenter after the scope of initialize method ends?
View/ViewModel obviously won't have reference to presenter unless VM/View has an event which is subscribed by presenter. We can go into an inconsistent state in which the view is active but the presenter is garbage collected.
To prevent garbage collection of presenter probably we'll need a KeepAlive property in ViewModel that just holds the reference to presenter for preventing its GC but that sounds hacky to me. What do you do or would do in this situation?
Please note that in a situation where there will be multiple instances of the view, registering the presenter with ContainerControlledLifetimeManager is not feasible. Also if the mode of communication for presenter (with view) is via commands and the commands happen to be DelegateCommands of prism then they will only keep weak reference to the presenter so that won't serve the purpose either.

This is a complicated question about lifetime. In this example in the Prism documentation, the implementation of the EmployeesPresenter hooks up to an event on the EmployeesListPresenter:
public EmployeesPresenter(
IEmployeesView view,
IEmployeesListPresenter listPresenter,
IEmployeesController employeeController)
{
this.View = view;
this.listPresenter = listPresenter;
this.listPresenter.EmployeeSelected += new EventHandler<DataEventArgs<BusinessEntities.Employee>>(this.OnEmployeeSelected);
this.employeeController = employeeController;
View.SetHeader(listPresenter.View);
}
This ties the lifetime of the EmployeesPresenter to the lifetime of the IEmployeesListPresenter. It is registered with the container like this:
this.container.RegisterType<IEmployeesListPresenter, EmployeesListPresenter>();
Not staticly or ContainerControlledLifetime, either. Now we have to look at the implementation of EmployeesListPresenter. Here is its constructor:
public EmployeesListPresenter(IEmployeesListView view,
IEmployeeService employeeService)
{
this.View = view;
this.View.EmployeeSelected += delegate(object sender, DataEventArgs<BusinessEntities.Employee> e)
{
EmployeeSelected(sender, e);
};
view.Model = employeeService.RetrieveEmployees();
}
Now we see that the EmployeesListPresenter is tied up in the lifetime of the IEmployeesListView.
So, the lifetime of the EmployeesPresenter is the same as the EmployeesListView, which will be essentially as long as it is in the control tree.
This is a pretty confusing sample. You will find that the Prism 4 samples are much more straightforward... I would recommend looking at them and possibly upgrading to Prism 4 if you have a choice.

Related

A Controller for MVVM

I'm working on a WPF project that's a mishmash of code-behind xaml/xaml.cs and a few not-quite ViewModels as well.
(Disclaimer: Until recently I've had very little in the way of WPF experience. I can design and lay-out a Window or UserControl fairly proficiently, and I think I get the hang of separating an MVVM ViewModel from the View and doing binding wire-ups, but that's the limit of my experience with WPF at present.)
I've been tasked with adding some new features to the program, such that it looks like converting it to use MVVM properly first is going to be necessary.
I'll demonstrate a specific problem I'm facing:
There is a View called SettingsWindow.xaml that I'm working with. It's a set of textboxes, labels and whatnot. I've stripped-out all of the View data into a ViewModel class which resembles something like this:
class SettingsViewModel : ViewModelBase {
private String _outputDirectory;
public String OutputDirectory {
get { return _outputDirectory; }
set { SetValue( () => this.OutputDirectory, ref _outputDirectory, value) ); }
}
// `SetValue` calls `PropertyChanged` and does other common-tasks.
// Repeat for other properties, like "Int32 Timeout" and "Color FontColor"
}
In the original ViewModel class there were 2 methods: ReadFromRegistry and SaveToRegistry. The ReadFromRegistry method was called by the ViewModel's constructor, and the SaveToRegistry method was called by MainWindow.xaml.cs's code-behind like so:
private void Settings_Click(Object sender, RoutedEventArgs e) {
SettingsViewModel model = new SettingsViewModel(); // loads from registry via constructor
SettingsWindow window = new SettingsWindow();
window.Owner = this;
window.DataContext = model;
if( dialog.ShowDialog() == true ) {
model.SaveToRegistry();
}
}
...but this seems wrong to me. I thought a ViewModel should consist only of an observable data bag for binding purposes, it should not be responsible for self-population or persistence, which is the responsibility of the controller or some other orchestrator.
I've done a few days' worth of reading about MVVM, and none of the articles I've read mention a controller or where the logic for opening child-windows or saving state should go. I've seen some articles that do put that code in the ViewModels, others continue to use code-behind for this, others abstract away everything and use IService-based solutions, which is OTT for me.
Given this is a conversion project where I'll convert each Window/View individually over-time I can't really overhaul it, but where can I go from here? What does a Controller in MVVM look-like, exactly? (My apologies for the vague terminology, it's 3am :) ).
My aim with the refactoring is to separate concerns; testability is not an objective nor would it be implemented.
I personally disagree with putting much in my ViewModels beyond the stuff that is pertinent to the View (it is, after all, a model of a View!)
So I use a Controller paradigm whereby when the View tells the ViewModel to perform some action (via a Command usually) and the ViewModel uses a Command class to perfrom actions, such as saving the data, instantiating new View/Viewmodel pairs etc.
I also actually separate my ViewModel and ViewData (the ViewModel 'contains' the ViewData) so the ViewData is puirely dealing with the data, the ViewModel with some logic and command handling etc.
I wrote about it here
What you need is called Commanding in WPF.
Basically you bind Button.Command to a ICommand property in your ViewModel and when Button is clicked you get a notification in ViewModel without using code behind and casing DataContext or whathever hacks you tried.
http://msdn.microsoft.com/en-us/library/ms752308.aspx

How to use MainWindow as ShellViewModel View?

I understand that by default CM will look for ShellView in Views folder to use as ShellViewModel View but I want to use the MainWindow instead... can this be done and how?
How it Works
CM uses a set of View/ViewModel Naming Conventions, generally speaking, if you have a ViewModel named FooViewModel CM will attempt to locate a type with a similar name of FooView or FooPage.
What if you really want "MainWindow" and "ShellViewModel"?
If you just wanted to use an existing "MainWindow" with an existing 'root viewmodel' then consider subclassing Bootstrapper<TRootModel> and override OnStartUp. This is a prescribed method, but can seem daunting.
(I have not tested this code.)
protected override void OnStartup(object sender, StartupEventArgs e)
{
var rootModel = IoC.Get<TRootModel>();
var rootView = new MainWindow();
ViewModelBinder.Bind(rootModel, rootView, this);
rootView.Show();
}
The above method, of course, would only apply to the initial view for the root view model shown during start-up. Future attempts to display a view for ShellViewModel may work, or they may result in errors, I am not certain.
Extending Conventions
There are a few ways to customize the convention itself. The most flexible and direct method is to intercept/hook Caliburn.Micro.ViewLocator.LocateForModelType, this allows you to modify the behavior/strategy applied during view location.
private static void CustomViewLocatorStrategy()
{
// store original implementation so we can fall back to it as necessary
var originalLocatorStrategy = Caliburn.Micro.ViewLocator.LocateForModelType;
// intercept ViewLocator.LocateForModelType requests and apply custom mappings
Caliburn.Micro.ViewLocator.LocateForModelType = (modelType, displayLocation, context) =>
{
// implement your custom logic
if (modelType == typeof(ShellViewModel))
{
return new MainWindow();
}
// fall back on original locator
return originalLocatorStrategy(modelType, displayLocation, context);
};
}
The above can be called from inside a Bootstrapper<TRootModel>.Configure override:
protected override void Configure()
{
CustomViewLocatorStrategy();
base.Configure();
}
This method is more likely to play well with CM (in terms of any view caching, namely.) However, it still breaks conventions, and it's still a fair amount of code.
Registering Additional Suffixes?
One thing I want to point out, but have not had a chance to play with, is ViewLocator.RegisterViewSuffix implementation. I believe if you executed ViewLocator.RegisterViewSuffix(#"Window") then you could rely on CM to map MainViewModel to MainWindow.
This would allow for more expressive suffixes (such as Window, Dialog, Form, or others you may want to use.) Personally I dislike the use of 'View' as a suffix, I believe it's too generic (after all, they are all Views.)
Caliburn.Micro doesn't look for ShellView by default, this is how things work. Let's say you have a bootstrapper defined like this:
class MyBootsrtapper : Bootstrapper<MyViewModel> { }
Then CM (Caliburn.Micro) will look for a view named MyView. So yes you can use MainWindow instead as long as your view model name is MainWindowViewModel.
I have answered the other question you have asked and it seems you don't fully comprehend CM so i really really advise you to Start Here and you can always check the projects Documentation on codeplex because it contains all updated information and documentation.
Edit:
Caliburn.Micro uses a simple naming convention to locate Views for
ViewModels. Essentially, it takes the FullName and removes “Model”
from it. So, given MyApp.ViewModels.MyViewModel, it would look for
MyApp.Views.MyView.
Taken from official documentation here.

MVP: Is it the View or the Presenter that should know of the Model?

Relatively new to patterns, let me straight away show an example in the context of WinForms.
I have a basic MVP Passive View structure, which one should I go ahead with:
public partial class UserView : Form, IUserView
{
public event EventHandler Save;
public UserView()
{
InitializeComponent();
new UserPresenter(new UserModel(), this);
}
}
public class UserPresenter
{
public UserPresenter(IUser model, IUserView view)
{
view.Save += (sender, e) => model.Save();
}
}
or
public partial class UserView : Form, IUserView
{
public event EventHandler Save;
public UserView()
{
InitializeComponent();
new UserPresenter(this);
}
}
public class UserPresenter
{
public UserPresenter(IUserView view)
{
var model = new UserModel();
//assuming I have the logic to bind property values from View to Model
view.Save += (sender, e) => model.Save();
}
}
My questions are:
1) Who should know of the concrete instance of model User, View or Presenter?
2) What will be the benefit in that case?
3) Suppose my Model is never dependent on the View. In that case what's wrong if View knows Model? After all UserView is made to present UserModel isn't it?
4) If Presenter should interact with only interfaces of Model and View, then to call model.Save in Save eventhandler, where do I get the concrete instance of Model from?
There are two duplicate questions here and here, but they aren't exactly dealing with my scenario I guess..
Strictly speaking, you should have the following rules:
Model does not know the View or the Presenter.
View does not know the Model or the Presenter.
Presenter knows both Models and Views, but only through their interfaces.
The Presenter coordinates all communication between the Model and the View, typically by handling events that are raised by the View. So to answer your questions:
1) Who should know of the concrete instance of model User, View or Presenter?
Ideally, neither. The Presenter should be communicating with UserModel through an IUserModel interface. The concrete instance is injected into the Presenter (e.g. through its constructor).
2) What will be the benefit in that case?
The primary benefit is for automated unit testing. You can inject mock Models or Views to test units in isolation.
3) Suppose my Model is never dependent on the View. In that case what's wrong if View knows Model? After all UserView is made to present UserModel isn't it?
There's nothing inherently wrong with it. There are variations of MVP that support direct communication from the View to the Model, typically to take advantage of data binding. You lose some testability in exchange for not having to write the binding code from scratch.
4) If Presenter should interact with only interfaces of Model and View, then to call model.Save in Save eventhandler, where do I get the concrete instance of Model from?
Depedency injection, such as the simplified example shown below.
public class SamplePresenter
{
public SamplePresenter(ISampleModel model, ISampleView view)
{
view.Saved += (sender, e) => model.Save();
}
}
public interface ISampleModel
{
void Save();
}
public interface ISampleView
{
void Show();
event EventHandler Saved;
}
public class Program
{
[STAThread]
static void Main()
{
ISampleModel model = new SampleModel();
ISampleView view = new SampleView();
SamplePresenter presenter = new SamplePresenter(model, view);
view.Show();
}
}
What's wrong if view knows model? After all UserView is made
specifically for UserModel isnt it?
Nothing. It's accepted practice in the Supervising Controller variant of the MVP pattern. The view interacts directly with the model for simple operations while more complex operations are marshalled throught the presenter. While in Passive View, everything goes through the presenter.
Additionally, see Jeremy Miller's Build your own CAB series to get a better idea on the differences between the two approaches: Supervising Controller and Passive View.
The Presenter should know about the Model, the View should not. A presententation layer is a good idea in many user interface applications. A presentation layer is simply an adapter. It presents an interface that's easy for a user interface layer to use (i.e., it presents lots of events, bindable properties, and so on) while obscuring the underlying data layer. This makes the data layer easier to re-use.
EDIT
So why can't the view just talk to the model directly? It certainly can. The problem is that there is usually an impedence mismatch between the model and the view. In other words, the programming interface that's natural for the view to use does not match the interface that's natural for the model to expose. If you adapt the model to suit the view's needs, then you end up creating a strong coupling between the model and the particular type of interface you're using.
For example, your app might be a GUI app today, but what if tomorrow you're asked to produce a version for the cloud? The events and bindable properties that are helpful for Winforms will just get in the way when you try to switch to WCF Rest. If you use a presentation layer, then adapting your code to the new environment will be much easier.
If it's not too much for your introduction to presentation patterns, I'd urge you to take a look at the Presenter-first variant of MVP.
In this variant, and providing an answer to your question, the presenter knows both the model and view but only via interfaces. Neither the view, nor the model know of each other. The presenter co-ordinates each via events and methods.
http://atomicobject.com/pages/presenter+first
http://spin.atomicobject.com/2008/01/30/presenter-first-get-your-triads-talking/
Example:
Class Presenter {
private IModel model;
private IView view;
void Presenter(IModel model, IView view) {
_model = model;
_view = view;
}
void Initialise() {
// Attach handler to event view will raise on save
_view.OnSave += HandleViewSave();
}
void HandleViewSave(){
_model.Save(_view.GetStuffToSave());
}
}
Very basic example but illustrates the point. The presenter is merely a conduit for communication between the view and model.
Creating the presenter can be done with Poor Man's DI or a proper container:
Presenter p = new Presenter(new CustomerModel(), new CustomerForm());
Note that AtomicObject recommend no reference to presenter, so it actually looks like this:
new Presenter(existingCustomerModel, existingCustomerForm);
existingCustomerModel.Initialise();
The fact that the model and view have scope means the presenter also stays in scope via its references... clever.

MVVM CollectionViews in WPF Application Framework (WAF)

In short my question is: How do you prefer to expose filtered/sorted/grouped ObservableCollections to Views in WAF?
I was fairly happy with my first attempt which involved filtering on the VM and exposing an ICollectionView of Model objects for the View to bind to:
public StartDetailViewModel(IStartDetailView view, StartPoint start, Scenario scenario)
: base(view)
{
this.scenario = scenario;
this.start = start;
this.startsViewSource = new CollectionViewSource();
this.startsViewSource.Filter += new FilterEventHandler(Starts_Filter);
this.startsViewSource.Source = scenario.Starts;
}
public ICollectionView FilteredStarts
{
get
{
return startsViewSource.View;
}
}
void Starts_Filter(object sender, FilterEventArgs e)
{
if (e.Item != null)
{
e.Accepted = (((StartPoint)e.Item).Date == this.start);
}
}
}
However, exposing the Model objects directly is insufficient since each item now needs its own ViewModel.
So, CollectionViewSource.Source is now attached to a collection of Views. The main problem with this is when applying filters:
void Starts_Filter(object sender, FilterEventArgs e)
{
//Since e.Item is now a view we are forced to ask the View for the ViewModel:
StartItemViewModel vm = ((IStartItemView)e.Item).GetViewModel<StartItemViewModel>();
[...]
}
This feels wrong to me. Are there better approaches?
UPDATE
So I reverted to a CollectionViewSource.Source of Model objects and maintained a seperate collection of child View objects to which the View was bound.
The question then of course is why am I using CollectionViewSource in a ViewModel at all?
I think the following prinicple applies: If the filtering/sorting functionality is a property of the View only (i.e. an alternate view might legitimately not provide such functionality) then CollectionViews should be used in the View (with code-behind as necessary). If the filtering/sorting functionality is a dimension of the Model then this can be dealt with in the ViewModel or Model by other means.
This makes sense once you realise that code-behind in MVVM views is perfectly acceptable.
Any comments?
I think the real benefit of CollectionView lies in when you are in need of reporting information as you step through collectionview items one by one. In this way you are able to utilize the CurrentPosition property and MoveCurrentToNext (/etc.) methods which may be desireable. I particularly like the idea of being able to report PropertyChanged notifications in MVVM when item properties in the collection changed/items are added/removed/changed.
I think it just makes a bit more sense to use in controls that require more complex notifications (such as datagrid, where you may want to raise PropertyChanged events and save to your datastore each time the selectionchanges or a new item is addd to the control).
I hope that makes sense. That is just what I am putting together as a beginner.
Also, I really don't think anything should go in the code-behind of a view except a datacontext and the shared data you may be feeding it from a viewmodel.

When to unhook events in Silverlight

One-line summary: What is the best practice for unhooking event handlers created in the constructor of a UserControl in Silverlight2?
Background:
I am currently building a line-of-business application in Silverlight2. As Silverlight is a browser plugin, there is no concept of a Window - everything is done within UserControls. The way I'm handling different "forms" in the application is to have a top-level usercontrol that contains a Viewbox. To show different forms, I set the Child property of the Viewbox to different UserControls. My app has a singleton PageManager class that is called to open and close forms. The forms (UserControls) are stored in a stack. Opening a form puts it on the top of the stack, closing it removes it from the stack and shows the one below it.
I'm trying to follow the Model-View-ViewModel pattern. In each form (derived from UserControl), I have a ViewModel that manages all the data for the View. The ViewModel exposes events so the UI can be notified when operations such as load and save have completed.
In my form, I subscribe to the event in the constructor, after I've got the ViewModel
public partial class MyPage : UserControl
{
public MyViewModel ViewModel{get; set;}
// other constructors, which create the viewmodel and call the constructor below.
public MyPage(MyViewModel viewModel)
{
InitializeComponent();
ViewModel = viewModel;
this.LayoutRoot.DataContext = this.ViewModel;
// subscribe to event so we can do stuff
this.ViewModel.LoadCompleted += new MyViewModel.LoadCompletedEventHandler(ViewModel_LoadCompleted);
}
My question is: Now that I've subscribed to this event, when do I remove the handler? Do I create a destructor and do it there, or does that create a chicken-and-egg situation where the garbage collector wont destroy the object until all references (ie: the event handlers) are gone? Do I create an interface that the forms must implement that specifies an UnhookEvents function that's called when the form is closed by the PageManager?
Edit: Thanks for the responses. What about the situation where the ViewModel lasts longer than the form (UserControl)? Part of my app allows users to create what is quite a complex structure, but in 95% of cases it's much simpler. What I've did was create 2 forms that use the same ViewModel. Users can start filling out the simple form, then switch to advanced mode, which creates a new form, passing the ViewModel to it.
In the simple setup form:
private void AdvancedSessionSetupButton_Click(object sender, RoutedEventArgs e)
{
PageManager.GetPageManager().Close(this);
PageManager.GetPageManager().Open(new CreateSessionPage(this.ViewModel), "Create Session");
}
In the advanced setup form:
private void BasicSessionSetupButton_Click(object sender, RoutedEventArgs e)
{
PageManager.GetPageManager().Close(this);
PageManager.GetPageManager().Open(new CreateBasicSessionPage(this.ViewModel), "Create Session");
}
After PageManager.Close, the only things referencing the form are the events within the ViewModel. I guess that's where I should be unhooking them.
A destructor, more commonly known to C# programmers as Finalizers, is not necessary in this case. Assuming that ViewModel_LoadCompleted is a member function, it contains a pointer to "this" which you are giving to the ViewModel object which is fully contained by "this". The garbage collector should intelligently ignore this.
In this case, the correct thing to do is to not waste time unbinding them.
In general, you need to unbind an event handler when you pass "this" (explicitly, or implicitly) to some object which will hold that reference longer than the intended lifetime of "this". For example, if you set a handler on a parent control's event. Now the parent has a reference to you via the handler as well as in its Children controls collection. In this case, you should unbind when you are removed from the parent.
When in doubt, implement IDisposable and unbind in the call to Dispose().
Events are automatically unbinded when the garbage collector goes through your object.
But you can explicitly unbind them with the "-=" syntax at anytime:
this.ViewModel.LoadCompleted -= ViewMode_LoadCompleted;
You can implement a destructor:
~MyPage
{
this.ViewModel.LoadCompleted -= ViewMode_LoadCompleted;
}

Resources