How to inject dependency into MVVM View Model class? How to inject dependency into MVVM View Model class? wpf wpf

How to inject dependency into MVVM View Model class?


Some times going back to basics and keeping things simple (KISS) tends to work.

What comes to mind for this scenario is The Explicit Dependency Principle and Pure Dependency Injection.

The MainViewModel is doing way too much as evident by either injecting the container (big no no) or have way to many dependencies (code smell). Try to narrow down what it is that class is suppose to be doing (SRP)

So let's say the main view model needs a collection of panes. Then why not give it what it needs.

public class MainViewModel : ViewModelBase {    public ObservableCollection<DockPaneViewModel> DockPanes { get; set; }    //Give the view model only what it needs    public MainViewModel(IEnumerable<DockPaneViewModel> panes) {        DockPanes = new ObservableCollection<DockPaneViewModel>(panes);    }    public void ResetPanes() {        foreach (var pane in DockPanes) {            pane.Reset();        }        //notify view    }}

Note the slight change to the base panel

public abstract class DockPaneViewModel : ViewModelBase {    // ...    public virtual void Reset() {        //...    }}

The main view model should not concern itself with how the dependencies are created. It only cares that it gets what it explicitly asks for.

The same applies to the different pane implementations.

If a view model needs to be able to create multiple children then delegate that responsibility out to a factory.

public class MonitorPageViewModel : DockPaneViewModel {    public MonitorPageViewModel(ILogger logger, IRepository<RawMessage> repository,        IRepository<Parser> parserRepository, IParsingService parsingService,         IPaneFactory factory) {        // ...    }    public void CreateDashboard() {        var dashBoardVm = factory.Create<MonitorDashboardViewModel>();                //...    }}

Again the subject should have as few responsibilities as possible.

View First or ViewModel First are considered implementation concerns and really does not matter if following a convention over configuration model.

If the design is well done, it really does not matter whether you use a framework or pure code.

Those frameworks though, do come in handy when it comes to putting everything together. The most simple and elegant solution is to have something create the object graph, but without that something, you are left to build it up yourself in the composition root.