Question

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... ?

Was it helpful?

Solution

You can register all of those types in the container, and have the OnStartup method make a single Resolve call.

First, have MainWindow accept its view model in its constructor:

public MainWindow(MainViewModel viewModel)
{
    DataContext = viewModel;
}

Then, register MainWindow and MainViewModel in the container right alongside the services. If MainViewModel requires other view models, put those in its constructor and register them as well.

Finally, resolve MainWindow, which performs all of the instantiation work:

var window = container.Resolve<MainWindow>();

window.Show();

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) MainViewModel is 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top