A.B.
A.B.

Reputation: 2470

What is the advantage of injection vm into view vs defining it in XAML when using Prism?

I usually define my viewmodels directly in XAML as following:

<Window.DataContext>
    <vm:MyViewModel />
</Window.DataContext>

Otherwise when ViewModel has constructor parameter, with an ObjectDataProvider.

In the official pdf documentation of Prism 5, they define it in the codebehind and inject the viewmodel with MEF/Unity as following:

[Export] 
public partial class Shell : Window 
{ 
    public Shell() { InitializeComponent(); } 

    [Import] 
    ShellViewModel ViewModel
    {
        set { this.DataContext = value; } 
    }
}

I personally use DI with MEF, but in that particular case, i really do not see any advantages of injecting the VM and think it as an overuse of DI.
(assumption: I do not write any huge Unit Test for GUI, which mimics the whole ViewModel, since my unit tests rely on the service layer. And even in that case I could switch the DataContext in a test case dynamically.).
But may be I am missing something.

So, what are the pros/cons between two approaches?

Upvotes: 0

Views: 115

Answers (1)

user5420778
user5420778

Reputation:

There are many issues with having your View responsible for creating your ViewModels, but I will just use one as an example; dependency management. Let's assume you have a VM defined:

public class MyViewModel
{
    public MyViewModel() { }
}

Lets assume you had your view created in XAML:

<Window.DataContext>
     <local:MyViewModel />
</Window.DataContext>

Now, what do you do when your VM needs a service or dependency?

public class MyViewModel
{
    public MyViewModel(IMyService myservice) { }
}

Even worse, what if that service has dependencies of it's own?

Well, now defining this in XAML is definitely out for obvious reasons. If you define the DataContext in code, you have a similar problem you had in XAML; dependency management. If you had injected the ViewModel, then you would never have to worry about what dependencies your ViewModel requires, and you would never have to modify your code-behind to accommodate a new dependency added to the VM ctor. It would just work. This especially comes in handy when your VMs are in a different assembly and shared across multiple platforms, or when you need to change which concrete implementation of a dependency to use based on the build configuration or device.

Upvotes: 1

Related Questions