A common question I have been seeing in the blogosphere when dealing with dependency injection (DI) is which comes first? The View or the ViewModel.
I have seen several approaches where the ViewModel receives a View via a constructor parameter. I have also seen another approach with the ViewModel receiving a View via Property injection. This limits how much support you get from Blend.
I have seen the approach where a View creates a ViewModel as a static resource and then the DataContext of the View is set to the key of the resource. I have seen the locator approach where you have a class that acts as the ViewModel service locator and then returns the correct ViewModel depending on your scenario. This actually comes in handy if you want to have Blend support.
The one concern I have with both of these goes to the heart of the question and that is who is going to write and maintain all of this ceremonious scaffolding? I believe that neither the View nor the ViewModel should be concerned with hooking each other up. I am currently using Prism developing Silverlight applications but the approach I am going to provide would work for either Silverlight or WPF.
Here goes….What I offer is that the true responsibility of hooking the View with the ViewModel or vice versus belongs to the dependency injection container. It should be the container who decides what to do and how to proceed. I am introducing a little convention to get this accomplished but I think you will find this to be an eloquent solution for shops that are more focused on maintenance and reusability.
What I have created is an extension method attached to the Unity container.
As you can see from above, I resolve the View and ViewModel from the Container first. Then I check by convention if there is a property named “View” on the ViewModel. If I find it, then I set the property with the value of the newly resolved View. Likewise, I check the View to see if it is a FrameworkElement and if it is, then I set the DataContext with the value of the ViewModel.
There you have it! I am sure that you can think of many other conventions or ways that you could make this work for your development shop.
Thanks for reading and stay tuned for more….