Another .NET Blog

To content | To menu | To search

Thursday 30 September 2010

[Caliburn Micro] How to use the same view for multiple view-models

The default behavior of Caliburn Micro (CM), when it must locate a view from a view-model, is very straightforward: it takes the full name of the view-model, replaces the word "Model" by an empty string, and locates a view with this new name.

One problem with this way is that you must exactly have one view per view-model. So, if you have an abstract view-model, with multiple derived view-models, which only set some filters on the displayed data, you must have one view per derived VM. Which is kind of annoying, useless, and error prone.

In this short article, I'll show you how to easily implement a new feature which will allow us to specify, with an attribute on top of the VM, the view we want CM to display when we activate the VM.

Continue reading...

Monday 23 August 2010

[Ninject] Use one database session per view-model

One very useful web page I've read before beginning to code on my new project was this one: Data Access - Building a Desktop To-Do Application with NHibernate, from the well-known Ayende. In this article, among other hints and best-practices, he says, at the end of the Managing Sessions chapter:

The recommended practice for desktop applications is to use a session per form, so that each form in the application has its own session. Each form usually represents a distinct piece of work that the user would like to perform, so matching session lifetime to the form lifetime works quite well in practice. The added benefit is that you no longer have a problem with memory leaks, because when you close a form in the application, you also dispose of the session. This would make all the entities that were loaded by the session eligible for reclamation by the garbage collector (GC).

There are additional reasons for preferring a single session per form. You can take advantage of NHibernate’s change tracking, so it will flush all changes to the database when you commit the transaction. It also creates an isolation barrier between the different forms, so you can commit changes to a single entity without worrying about changes to other entities that are shown on other forms.

While this style of managing the session lifetime is described as a session per form, in practice you usually manage the session per presenter.

We'll see now how to implement this behavior, with Caliburn as the MVVM client framework, and Ninject as the dependency injector.

Continue reading...