问题
I'm new to WP 7. For purposes of dependency injection, I want to adhere to practices acquired doing WinForms apps. I therefore want to build my app graph at the composition root. What part of a regular WP 7 app source code can be viewed as the composition root?
回答1:
The pattern I prefer, as recommended by the Patterns & Practices team, is:
- Add a
ViewModelLocator
class to your resourcesApp.xaml
with anx:Key="ViewModelLocator"
, and add to that class a property for each ViewModel type and lazy-instantiates the VM using the container. - Configure your dependencies in the application constructor (
App()
in App.xaml.cs) and provide the container instance to theViewModelLocator
(viaApplication.Resources["ViewModelLocator"]
) - Bind the ViewModel to each page by assigning
DataContext="{Binding ViewModelPropertyName, Source={StaticResource ViewModelLocator}}"
See the WP7 Guide for a working implementation.
来源:https://stackoverflow.com/questions/7310162/where-is-the-composition-root-in-a-windows-phone-app