I have this code:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var mainVM = new MainViewModel
(
new Service1(),
...
new Service10(),
);
var window = new MainWindow();
window.DataContext = mainVM;
window.Show();
}
}
I pass all my Services instances to the MainViewModel. Within the MainViewModel I spread those services to other ViewModels via constructor parameter passing.
Should I use any DI framework for the services in the App class?
If yes whats the benefit of resolving the services instead of just creating the instance manually… ?
You can register all of those types in the container, and have the
OnStartupmethod make a singleResolvecall.First, have
MainWindowaccept its view model in its constructor:Then, register
MainWindowandMainViewModelin the container right alongside the services. IfMainViewModelrequires other view models, put those in its constructor and register them as well.Finally, resolve
MainWindow, which performs all of the instantiation work:The key point here is that a view model is no different from any other class you would register in a container.
Advantages to this approach (from comments):
1) The container makes all the constructor calls for you – you simply have to describe each piece of the graph, and it goes through the tedium of assembling it.
2)
MainViewModelis freed from having to know how to construct its child view models, which lets it focus on its core responsibilities instead of having to know every single depedency of its children.