Reputation: 471
I have just read this article about MVVMC pattern. Now I have a question. Should Controller be injected to ViewModel, or ViewModel should be injected into Controller?
Upvotes: 8
Views: 10580
Reputation: 528
I believe the Controller should be injected as an abstraction IController. The ViewModel needs IController to be able to navigate to a different View/ViewModel.
For example, in ViewModel:
IController _controller;
public MyViewModel(IController controller){
_controller = controller;
}
void NavigateHome();
{
_controller.NavigateHome();
}
The abstraction IController is better than injecting the Controller itself for these reasons:
I developed a lightweight framework for doing MVVMC in WPF. It has a lot of resemblance to MVC in Asp.NET Core.
Check it out if you're looking for a WPF solution.
Blog post with documentation: http://michaelscodingspot.com/2017/02/15/wpf-page-navigation-like-mvc-part-2-mvvmc-framework/
GitHub: https://github.com/michaelscodingspot/WPF_MVVMC
Upvotes: 0
Reputation: 181
The MVVMC is simply a MVC where the View is replaced by a ViewModel pair.
I have put together a simply sample based on the well know sample of Josh Smith on MSDN... where I have introduced a Controller.
Upvotes: 9
Reputation: 7951
It depends on what you are doing. I'm going to guess that most of the time the Controller would not need to be injected into either, but if it is needed, it is more likely to be needed in the ViewModel. Let me explain.
What are you doing with the controller? You must be doing something.. If that "something" is solely related to "what the data looks like", then it belongs in the View. If it is related to "what is be being shown to the user" then it belongs in the ViewModel.
I'm injecting a controller into one of my ViewModels. My ViewModel represents data which is then graphed in the View. I have a command which moves a data item from the current graph to a new graph. Since this changes "what is being displayed in the graph window" I implemented the command in my ViewModel. The ViewModel removes the data item from its own collection of items, and then uses the Controller to request a new view be created for that new data (it already had this functionality).
Looking at the article, I don't see arrows between the controller and the view
Upvotes: 5
Reputation: 926
The ViewModel is a contract between the View and the Controller, and ideally does not need to know about (be dependent on) either.
So I definitely wouldn't be injecting a Controller into a ViewModel.
I'm not sure I'd be doing the opposite either: the controller is normally responsible for creating new ViewModel instances. If you want to go for a more loosely coupled implementation, you could go for injecting an abstract factory into the Controller, to avoid directly creating new instances of your ViewModel classes.
Upvotes: 0