Call service via VM/command or code-behind

Topics: Questions
Jun 19, 2012 at 12:39 PM
Edited Jun 19, 2012 at 12:43 PM


I created a service "LayoutManagerService" which is responsible for saving layouts/restoring layouts (view's controls position/size(order,...). In the constructor of my view I get a LayoutManager responsible for the view from the service, where I register my view/controls and load/safe the default layout.

So far no VM is involved. But now what if the user wants to save a new layout. Should this call a command on the viewModel and this command call my Service.

Or could/should I stay in code-behind. handle an event and call the manager's methods directly.


I think I should stay in code-behind, because no model data is involved, it just affects the lookingof the view, but I'am not sure.

Jun 19, 2012 at 3:25 PM

What I normally do (I am actually working on such a thing also), is to send out a message. This way, the view is always responsible for it's own serialization. The view can register to messages sent by the Message Mediator.


1) Send a message in the VM when the user handles a command to save/load a layout

2) In the view, receive this message and handle the right calls to the service.

But in the end, since you already abstracted it all away in a service, it doesn't matter that much.

Jun 21, 2012 at 8:45 AM

Ok, that sounds nice with the mediator.

But I have an idea of doing it this way (maybe this is completely bad):

My LayoutManagerService is registered in the service locator. Because of this and that the LayoutManger responsible for the view lies in my service , I could call directly my service and the LayoutManager from the ViewModel or the whole app. All would stay loosly coupled. But then not only view is responsible, but in real it is the LayoutManager who is responsible.

Does it matter that the LayoutManger Methods are called not only from the view? Are there any problemes with it?

Jun 21, 2012 at 2:55 PM

No, like I said in the end it doesn't matter much because you already abstracted it all away in services. For example, a messageservice is responsible for showing a messagebox. Is this bad? No, for two reasons:

1) You separated the view-related stuff from the view model

2) You can replace the IMessageService (in your case ILayoutManager) by a dummy implementation and unit test your view model (in the end, isn't that one of the reasons you actually want separation of concerns :))