I'm pretty novice to WPF/MVVM and trying to understand this pattern. I'm exploring this MVVM application http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
Author created Customer
class which is stored in Model
folder and CustomerRepository
class which is stored in DataAccess
folder
CustomerRepository
contains methods that 'do stuff', for example static List<Customer> LoadCustomers(string customerDataFile)
I.e. we can't say that CustomerRepository
is pure model file, it's also kind of utility file.
From another hand CustomerRepository
stores important data readonly List<Customer> _customers;
and we know that we should store such kind of data in model!
Well I would say that CustomerRepository
is mixing things - it's a model file that contains some utility methods inside it.
The problem is that CustomerRepository
instance is passed to ViewModel public AllCustomersViewModel(CustomerRepository customerRepository)
. Now viewModel contains something that it shouldn't, in particular it can force CustomerRepository
to reload stuff etc.
In my opinion this is agains MVVM pattern, I think that ViewModel should only contain references to model files all utility classes and methods to manipulate model files should be in other places.
Am I right or wrong? Is it ok to pass class that offers some services on model (can reload/refhresh model etc.) to ViewModel? I.e. where should be so-called service layer
, is it ok to have it in ViewModel?
AndroidViewModel. Application context aware ViewModel . ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment . It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).
android.arch.lifecycle.ViewModelProvider. An utility class that provides ViewModels for a scope. Default ViewModelProvider for an Activity or a Fragment can be obtained from ViewModelProviders class.
You are wrong in your assumption that "ViewModel should only contain references to model files".
ViewModel can reference anything it needs, as long as it isn't a view.
It is very common to inject services into a ViewModel.
AFAIK, there are two widespreas treatments of the MVVM pattern.
The first, which you seem to be more familiar with, includes 4 components: View, Model, ViewModel and Controller. Here, ViewModel contains only UI logic and exposes events to Controller which serves for synchronization between ViewModel and Model.
The second, which is used in the article, simply merges ViewModel and Controller into ViewModel. BTW, Martin Fowler describes this case: http://martinfowler.com/eaaDev/PresentationModel.html
The choice depends on personal preferences as I see it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With