Thursday, 6 June 2013

Building a Windows Store app using Prism and manual dependency injection

Previously I’ve demonstrated how to use Prism for the Windows Runtime by writing a sample photo viewing app. In the app there are two pages. The first page presents a thumbnail gallery view of photos in the users Pictures library. Clicking on a thumbnail takes the user to the second page which displays the full image. In the app, support for MVVM, navigation, and state management are all provided by Prism for the Windows Runtime.

The app registered types and instances that are used in the view model constructors with the Unity dependency injection container. However, you are not required to use Unity, or any other dependency injection container, when bootstrapping Windows Store apps using Prism. An alternative approach is to perform manual dependency injection to pass client service references to view models by registering factory methods against view types, in the App.OnInitialize method.

protected override void OnInitialize(IActivatedEventArgs args)
    var FileSystemRepository = new FileSystemRepository();
    ViewModelLocator.Register(typeof(MainPage).ToString(), () => new MainPageViewModel(FileSystemRepository, NavigationService));
    ViewModelLocator.Register(typeof(PhotoPage).ToString(), () => new PhotoPageViewModel(FileSystemRepository, NavigationService));

This method creates a singleton from the FileSystemRepository class, The FileSystemRepository class provides image data for display on both pages of the app. The OnInitialize method then registers a factory method for each view type with the static ViewModelLocator object, This ensures that the ViewModelLocator object instantiates the correct view model object for a view type, passing in dependent services to the view model constructor from the factory method. This alternative approach avoids using a dependency injection container, for those who prefer not to.


Prism for the Windows Runtime can accelerate the development of Windows Store apps by providing support for MVVM, loosely coupled communication, and the core services required in Windows Store apps. As well as allowing you to use a container for dependency resolution and construction, Prism also allows you to explicitly specify how to construct a view model for a given view type.

The sample app can be downloaded here.

No comments:

Post a Comment