tags:

views:

17

answers:

1

I come up against this decision frequently and I constantly vacillate on what approach to take.

Many MVVM examples have the model being passed into the constructor of the view model. Hence every VM is coupled to a Model. The logic to retrieve the Model and create the VM is outside of the VM "somewhere". Model has to know how to persist it changes.

The other option is to pass some sort of context, service or repository through to the VM and the VM decides what model it needs. The implication is the VM has a longer lifetime and might be reused to display many different models. The VM will commit changes to the model back using the supplied service.

Has anyone come up with any rules for working out the best approach for a given scenario?

A: 

A ViewModel is generally defined to be a View on a Model, i.e. it exists to mediate between the Model and a View. While it would be perfectly possible to have a ViewModel that is generic enough to mediate for multiple Model types, in practice the reverse is true and multiple ViewModels may exist for a single Model type, particularly in those cases where a single Model needs to be rendered in different ways in different parts of the application.

Also, I normally treat the Model as being a simple data object and implement retrieval and persistence logic in a separate service which can be passed in using dependency injection. Having said that, there is nothign wrong with building persistence logic directly into the model if that fits your scenario better. I do prefer, though, to split that layer out so as to allow for easier testing via mocking.

Mark Green