I have a question about MVVM design, and where I should put some code that I would like to add.
My application queries active directory for computers and displays the list to the user. Selecting a computer displays some general Active Directory and WMI information about that specific computer.
Currently, I have a "MainWindowViewModel" for the application main window. Each Computer gets its own "ComputerViewModel". ComputerViewModels communicate with a DataService, which in turn uses the ActiveDirectory and WMI repositories to get the information.
I would like to indicate whether or not the machine is "up" by pinging it. Is it considered OK MVVM practice to put the pinging code in the ComputerViewModel, or should I put that somewhere else?
-
ViewModels are a part of the presentation layer. Pinging doesn't seem to belong in the presentation layer. I wouldn't put the pinging code into a ViewModel.Nick Alexeev– Nick Alexeev2018年11月13日 18:09:42 +00:00Commented Nov 13, 2018 at 18:09
1 Answer 1
Personally, I like to keep each ViewModel as empty as possible - only including methods / properties that are directly responsible for providing data to the View, as the shell of an ICommand triggered function, or to record runtime object state. Everything else goes into (injected) services.
So in your case, the Ping() functionality would go into the IDataService, just taking a computer Model instance as a parameter (for the Id or connection properties of that computer). The computer view model would have a property something like IsConnected or ConnectionStatus which is set from the return value of Ping().
I covered this separation between ViewModel and services in a recent blog post.
-
I think that makes a lot of sense. Thanks for your feedback.bdan– bdan2018年11月14日 13:09:12 +00:00Commented Nov 14, 2018 at 13:09