Reputation: 16980
Can you please give an example of how you would use (your favorite) DI framework to wire MVVM View Models for a WPF app?
Will you create a strongly-connected hierarchy of View Models (like where every nested control's ViewModel is a property on a parent's ViewModel and you bind it to nested control's DataContext in XAML) or you would use some kind of even-more-abstract ""View Model" Manager", which maintains some weakly-connected hierarchy... like in CAB, maybe?
Upvotes: 12
Views: 16100
Reputation: 178630
If a view model can only exist in conjunction with another, I create a strong relationship. That is the owning view model will have a direct reference to one or more of the dependent view models. If, on the other hand, a view model should be able to exist with or without another, I take a loosely-coupled approach where they communicate via an event bus.
In terms of using DI with MVVM, absolutely you can combine the two. It's as simple as:
public class MyViewModel
{
private readonly IMyDependency _myDependency;
public MyViewModel(IMyDependency myDependency)
{
_myDependency = myDependency;
}
}
Note, however, that this assumes a "view model first" approach to MVVM, which has its drawbacks.
Upvotes: 6
Reputation: 13839
I published this article on Code Project about how to make an extensible WPF app using MVVM and MEF for extensibility. However, if you look closely, I used MEF for DI as well.
The application is fully MVVM and only uses DataTemplates (and the occasional Window) for Views, just like in Josh Smith's article. WPF takes care of applying the correct View to the right ViewModel for you. It's sweet.
It uses MEF so that the parts can "find" each other. So the ViewModel for the "View" menu item finds all the menu items that are supposed to be in the submenu using extension points, and the ViewModels for each of those "find" the ViewModel they're supposed to hand to the layout manager using composition points. They also "find" the layout manager service using a rudimentary service locator (MEF). The View menu example is almost precisely what you're talking about with nested ViewModels. The cool thing is they don't even know about each other until runtime.
Upvotes: 1
Reputation: 233125
In WPF it's normally pretty easy and it doesn't really depend on any particular DI Container. Have you read Josh Smith's article on MVVM? It pretty much describes how to set up a hierarchy of ViewModels.
What it doesn't go into much is how to create those ViewModels from dependencies (such as Repositories), but it's not a difficult extrapolation to do.
I've often experienced that liberal use of Abstract Factories helps quite a lot in this regard. Instead of directly new'ing up ViewModels I let an injected Factory do it for me.
You can use Poor Man's DI or any kind of DI Container to wire up such Factories for you.
Upvotes: 3