How can I combine MVVM and Dependency Injection in a WPF app?
c#, dependency-injection, mvvm, wpf
Solution
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.
Problem
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?