Prism for WinRT Applications–Sketchy Explorations

Following up on my previous post about Prism for WinRT applications, I thought I’d start digging in and trying to see what’s present in the Prism framework libraries.

I wasn’t entirely sure how to approach this. With the Prism bits you get three things;

  1. The Prism libraries for Windows Store applications
  2. A number of quick-start projects
  3. The AdventureWorks Shopper application

and then there’s also a bunch of documentation that you can either read online or download.

I thought about a few different ways that I could start to explore what was there. One thing I’d point out is that I have a bit of an aversion to samples so I tend to look at samples last rather than first and I know a lot of people work the other way around so bear in mind while you’re reading this that I have a particular way of going about these things and that these are really just my slightly scrappy notes as I try and poke around the new Prism framework and figure out what’s there for a Windows Store app.

If you want the definitive guide – read the definitive docs Smile

The Docs

I started with the docs. At the time of writing, I haven’t completely finished reading them but what I’d say from my first reading is;

  1. They are quite big at around 200 pages.
  2. They are surprisingly readable for a 200 page document.
  3. There’s a lot in there that is going to be useful to you whether you ever use the Prism framework or not. If you’re building a Windows Store app (or a Phone app) then I think these docs are still very much worth a read as they cover a lot of ground. Here’s some topics that I was not expecting to find in the Prism docs;
    1. “What is MVVM?”
    2. “Adding design time data”
    3. “Reading error messages from resource files”
    4. “Making key decisions about touch”
    5. “Handling suspend, resume”

and so on – it’s a long list of really useful and thought provoking topics for anyone who’s thinking about building an app.

As an aside, one of the things that I’m not overly keen on is seeing Prism describing itself as guidance for “Windows Store Business Applications”.

For me, I don’t really see the guidance as being anything specific to business applications. I see the guidance as being for writing good, structured, layered, maintainable applications. I don’t think those attributes should only be thought about in the context of business applications – they need to be applied to all applications that are going into the Windows Store and I’d almost say that they are more important for consumer applications because at least in a business you typically have a closer relationship with the end user whereas in a general Store, you need to make sure your app is solid from day one as your consumer isn’t likely to drop you an email if the app doesn’t meet their expectations.

Other than that, I think the docs are great and really deserve a proper read and I’ll finish my own reading of them in the coming days.

The Framework/Libraries

The next thing that I wanted to do was to have a poke around the libraries themselves. The package distributes;


and so I figured that I’d start off in the world of the pub-sub-events folder and then poke into the StoreApps folder and, from time to time if I get stuck, maybe I’d drop into the Quickstarts folder to see if that helped me figure things out.


The idea of the pub-sub events project is to promote loosely coupled events.

In .NET events are first class citizens of the languages like C# and VB but there’s a tight coupling between ClassA and ClassB if the former wants to handle an event raised by the latter – they need to know about each other from a typing perspective if they are going to achieve that. They also will need to know about whatever type represents the event data that’s passed from the source of the event to the sync of the event but that’s pretty much unavoidable.

As an aside, I’m reminded a little bit of the old notion of “connection points” in COM which had a form of loosely coupled events based around (being COM) interfaces rather than implementation types but that’s really “another story” so let’s leave that alone.

In Prism, there’s this notion of an EventAggregator which looks like this;


The fact that EventAggregator implements an interface means that a class can make use of it without taking a hard dependency on anything other than the interface type ( i.e. with no hard dependency on the implementation type EventAggregator itself ). It also means that it’s easy to register an event aggregator into some Inversion of Control (IoC) container and have it resolved dynamically to some type which implements IEventAggregator.

What does it do? It provides a dating agency for events.

Let’s say that I’m building an app which can be used anonymously but, equally, can be used by a logged on user and the decision as to whether to login or not might be up to the user and it might be possible for the user to login at any time during the lifetime of the application (perhaps it’s on the Settings charm in Windows 8).

When the user logs in, I might need to fire an event around the application to let “interested” components know that the user has logged in or logged out. Let’s say that the event payload looks like;

  public class LoginStatus
    public bool IsLoggedIn { get; set; }

    public string UserName 
        if (!this.IsLoggedIn)
          throw new InvalidOperationException("Not logged in");
        return (this._userName);
        this._userName = value;
    string _userName;

If I wanted one component to be able to “publish” an event of this “shape” and another component to be able to “subscribe” to an event of this “shape” then the only thing that I really want to share between those 2 components is the “shape” of the data class itself along perhaps with any common “pub/sub” infrastructure that I’m prepared to take a dependency on to get the job done ( in this case, that infrastructure is Prism PubSub Events ).

I’d need to create an EventAggregator somewhere;

      // Ok, so in this instance I know where my aggregator is coming from
      // because I'm creating it but let's pretend it's in a container.
      EventAggregator aggregator = new EventAggregator();

      // Let's treat the aggregator as though we don't know very much
      // about it.
      IEventAggregator abstractedAggregator = aggregator;

Now, assuming that I have some code that “knows” how to locate an IEventAggregator and that the code “knows” about the previously defined LoginStatus class I could define an event args class which will “carry” the LoginStatus event data;

  public class LoginStatusChangedEventArgs : PubSubEvent<LoginStatus>

and then I could publish an event;

      LoginStatus newLoginStatus = new LoginStatus()
        IsLoggedIn = true,
        UserName = "Mike"


and then some other component can subscribe to receive events of that particular shape – e.g.

      IEventAggregator abstractedAggregator = aggregator;

        loginStatus =>
          // Do something with the new login status.

Now, there are some bits in there which I left out and there are some additional nuances that the library does around this event publication/subscription functionality.

Firstly, what does PubSubEvent<T> look like? Putting that onto a class diagram really involved putting most of the rest of the pub sub library code onto a diagram;


In short – PubSubEvent<T> is a class that maintains a list of subscribers to an event of “shape” <T> and knows how to publish data of shape <T> to those subscribers. It has some additional smarts though which can best perhaps be seen by looking for all the overloads of the Subscribe() method;


We can subscribe to an event of a particular shape but we can also specify on which thread we’d like that subscription delivered;

  1. Dispatched on whatever thread the publisher calls the Publish() method from.
  2. Dispatched to the synchronization context represented by the SynchronizationContext property on the EventBase base class – this would usually mean “the UI thread” but it could be any arbitrary synchronization context.
  3. Dispatched from the .NET thread pool.

and we can also specify a filter (Predicate<T>) to filter when we’d like the event subscriptions delivered to our subscriber. For instance – in my example I might only want events delivered if the user was logged in or logged out.

Finally, there are some smarts here around garbage collection – that is, if objectA makes a subscription to an event then should that subscription keep objectA alive in the absence of any other references to objectA or should objectA get garbage collected?

If you look at the class diagram, this is where IDelegateReference and DelegateReference come in – these are being used to keep weak references (where requested) to the delegates provided for any filtering and for the subscription itself.

I think this is an important topic because in MVVM applications you might often want to use this form of loose-event communication to get a piece of data from ViewModelA to ViewModel B. However, it’s often the case that two otherwise unrelated view models would have mutually exclusive lifetimes and so this idea of which components are “alive” and when they are “alive” becomes important.

Subscribing returns a SubscriptionToken and that is needed to be kept for a call to Unsubscribe (subject to all I’ve just said about weak references Smile) and disposing of a SubscriptionToken looks to be equivalent to passing it to the Unsubscribe() method.

One last things about the pub-sub library – it is portable so you can build code into a portable class library that makes reference to this code and then use that library from any .NET (4+), Silverlight (4+), Windows Phone (7.1+) or Windows Store application.


As you might expect, there’s quite a lot more in the Prism.StoreApps project than there is in the pub/sub events project. One of the things that occurs to me first when looking at this code is that it perhaps could be re-factored to extract it out into more than one library because some of the code in here is not specific to building a Windows Store application and so might gain from being packaged as a separate library to get some re-use from other kinds of app projects (e.g. Windows Phone).

The DelegateCommand Class

An example of that would be this DelegateCommand class;


This is a class which takes a couple of delegates and puts an ICommand interace on top of them.

Everyone in the MVVM world needs this kind of class and most people have written it once or twice themselves and it really belongs in the .NET framework but it’s good that it’s here in this library. That said, I’d argue that this is not specific to building Windows Store apps – it’s applicable in Windows Phone, WPF and Silverlight apps too so could maybe be packaged separately.

Regardless, while we’re looking at it – it’s a simple way to make a command on a view model. So, if you have some view model;

  public class MyViewModel  
    DelegateCommand _someCommand;

    public MyViewModel()
      _someCommand = new DelegateCommand(
    void OnSomeCommand()
    bool OnCanExecuteSomeCommand()
      return (true);

then you can use DelegateCommand to provide an ICommand implementation for you over the top of one or two delegates ( one for execution, one for “can execute” ) and there’s a method there for raising the CanExecuteChanged event of ICommand. It’s worth saying that you can omit the “can execute” delegate and the class defaults to returning true to signify “Yes, I can execute”.

The ViewModel Class

The MyViewModel class I just wrote wouldn’t get me very far – it’s well understood that it needs to implement INotifyPropertyChanged so there’s a base class in the Prism framework that gives me an implementation of that interface – it’s called BindableBase;


and anyone who’s looked at the Windows Store templates in Visual Studio 2012 will be familiar with BindableBase and will know that it implements INotifyPropertyChanged for you and will (like me) be scratching their heads as to why this still isn’t in the .NET framework around 8 years after we first started to need an implementation of INotifyPropertyChanged. Anyway, it’s here in this library so that’s a good thing.

Looking a little further, it’s clear that the Prism ViewModel base class does more for us than just INPC. It also provides two other pieces of functionality;

  1. It implements INavigationAware such that if an app has a Page1/ViewModel1 which drives a navigation to Page2/ViewModel2 and possibly passes a parameter as part of that navigation then it’s possible for the ViewModel2 to pick up that parameter and do something with it. Anyone who’s been along to my recent Windows Phone sessions will have seen me build an interface and implementation a little like this to solve this exact same problem so it’s nice to see something like this here in Prism. Without something like it, it can be a bit tricky to have a view model get access to navigation parameters from the built-in navigation service which is somewhat tied to the UI classes.
  2. It has a notion of a state dictionary – this is for the app lifecycle management situations in a Windows Store application where we need to suspend an app and save its state away which potentially means saving the state of views, view models and services. This is how Prism builds support for the view model being able to plug-in to that requirement.

It turns out that these things work together. Having a look at those two methods;


If we accept that there’s some componentry somewhere which can hook into Windows 8 Suspend/Resume and navigation such that;

  1. when we are suspending the app that componentry can call a ViewModel’s OnNavigatedFrom method and ask it to populate a state dictionary which can then be persisted along with the navigation history (depending on the navigation mode).
  2. when we come back to an app in the case where the app was terminated by Windows that componentry can restore the navigation history, restore the view and the ViewModel and then pass into the OnNavigatedTo method the stored dictionary

then this can be used to suspend/resume ViewModels. The base ViewModel class already does this in that it looks for any properties on the ViewModel which have a custom attribute applied to them;


and it automatically grabs their values and stores them into the dictionary. Where this dictionary is stored is a mystery at this point in my exploration but I’m sure it’ll become clear later on Smile

The ViewModelLocator Class

One of the pain points in MVVM is always in trying to decide the Chicken/Egg situation between a View and its ViewModel and how they get instantiated and learn about each other ( by which I mean the ViewModel becomes the DataContext of the View ).

The Prism library has a ViewModelLocator class to help with this. It’s pretty simple to understand but that’s not to say that it’s not useful or powerful. Here it is;


and it’s probably not immediately obvious from that picture that it brings with it a an attached property called AutoWireViewModel. What that means is that I can author a view in an app like this;


and the presence of that AutoWireViewModel property is going to cause the ViewModelLocator class to attempt to “magically” set the DataContext of this view for me. How does it do that?

  1. The class maintains a list of factories. It’s a simple mapping from a type name (the type name of the view) to a factory function which is used to create the ViewModel. That list of factories can be appended to using the Register method.
  2. If the factories list doesn’t know how to produce the view in question then;
    1. The defaultViewTypeToViewModelTypeResolver is used to try to map from the Type of the view to the Type of the ViewModel.
      1. This resolver can be overridden by calling the SetDefaultViewTypeToViewModelTypeResolver method.
      2. Without any overriding, the class will essentially try to take the name of the View type and manipulate the namespace to change “Views” into “ViewModels” and “View” into “ViewModel”. This would mean that if you have a Views folder in your project with classes ending in …View then they would be matched up with classes ending in …ViewModel in a corresponding ViewModels folder.
    2. The defaultViewModelFactory is used to try and create the ViewModel.
      1. This factory can be overridden by calling the SetDefaultViewModelFactory method.
      2. Without any overriding, the class will try to use Activator.CreateInstance() to create the ViewModel.

This is all nicely lined up to allow for dependency injection. At application start-up time it’s easy to grab hold of the ViewModelLocator and call its SetDefault…X methods to pass in functions which can delegate the work of creating ViewModels to a IoC container.


Navigation can be a bit of a struggle in an MVVM app. The main problem is that navigation is performed by a Frame which is a UI construct and we don’t usually have reference to UI constructs in a ViewModel which means that we usually need to have some abstraction of a navigation service which make the services of the Frame available from within a ViewModel without exposing the details of the Frame itself to the ViewModel.

The other struggle with navigation is that it works differently on Windows 8 to how it works on Windows Phone 8 which means that a developer wanting to target both with a single codebase has to do some more abstraction work.

The Prism libraries have abstracted a navigation service. The essence of this is the INavigationService interface;


where the Navigate method has moved towards a hybrid of the Windows 8 style implementation where you navigate to a Type of page and pass a parameter of type object and the Windows Phone implementation where you navigate to a URI with the parameter embedded within it.

The Navigate() method looks like;


so you’re navigating based on some string plus an object parameter and that string can then be mapped onto some actual view type at a later point.

A ViewModel (or some other component) can then take a dependency on INavigationService and an implementation of the service could be injected. In the framework, there’s an implementation called FrameNavigationService;


Initially, I’d have perhaps expected the FrameNavigationService to make direct use of a Frame but, instead, it further abstracts its dependence on a Frame by hiding it behind IFrameFacade. That interface (which has interesting GetValue/SetValue methods on it like it was derived from DependencyObject) is then implemented by another class FrameFacadeAdapter which implements it on top of an actual (Windows 8) Frame;


The FrameNavigationService needs an IFrameFacade to work but it also depends on two other bits of functionality;


One is a function that knows how to resolve a string parameter into a Type. When the navigation service is asked to Navigate(“foo”) it can pass that string through the navigationResolver in order to map from the string name to an actual view type.

The other service that’s required by the FrameNavigationService is the ISessionStateService;


The provided implementation of this session state service (SessionStateService) firstly has a Dictionary<string,object> called SessionState which is publicly accessible can be used to store the objects that represent global state and the methods SaveAsync() and RestoreSessionStateAsync() will write/read that dictionary into a file in much the same way as the SessionStateManager class from the Visual Studio templates does (possibly with the addition of encrypted data).

In order to save those objects stored in the state dictionary, they will need to be serializable with the DataContract serializer and any additional types that the serializer needs to know about need to be registered via the RegisterKnownType() method.

The other thing that the class does is to manage a set of frames (represented by IFrameFacade here) although most apps will perhaps have a single frame. Frames (IFrameFacades) can be registered with the service via the RegisterFrame(IFrameFacade facade, string sessionStateKey) method.

Registration stores the session key passed with the IFrameFacade on the IFrameFacade itself (via the SetValue method) and stores a weak reference to the IFrameFacade in a list held by the SessionStateService.

Essentially, in combination with the GetSessionStateForFrame(IFrameFacade) method, a slot in the SessionState is reserved for the frame using the session state key for that IFrameFacade. That slot stores another Dictionary<string,object> specifically for the frame. A weak reference to the frame is also stored in a list inside of the SessionStateService.

So, we end up with a Dictionary<string,object> where some of the entries are more Dictionary<string,object> for any frames that have registered a key to store their state.

When the state service is saving state, it walks its list of IFrameFacades and makes sure that each one records its current navigation state into its own dictionary and then the service writes the whole “master” dictionary to a file.

The FrameNavigationService ties all these things together. Most of its “work” is delegated down to the IFrameFacade (which in turn delegates down to the Frame) so for simple things like;

  1. GoBack()
  2. CanGoBack()
  3. ClearHistory()

not much happens.

When it comes time to Navigate(), the service uses the navigationResolver to translate the string that has been passed to Navigate() into a Type parameter before asking the underlying IFrameFacade to actually Navigate() which, in turn, will ask the underlying Frame to Navigate().

Finally, the service effectively adds the “idea” of navigation support to ViewModels.

The service attaches event handlers to the IFrameFacade’s Navigating and Navigated events such that whenever navigation occurs, the IFrameFacade is interrogated to see if it contains Content and if that content is a FrameworkElement then that can be used to obtain a DataContext and, finally, if that object living in the DataContext implements INavigationAware then that provides a means via which the ViewModel can be notified as the app is navigating to/from the page that is loading that ViewModel.

This is done via INavigationAware.OnNavigatingTo and INavigationAware.OnNavigatingFrom and it’s a means via which the ViewModel can;

  1. Pick up the navigation parameter.
  2. Pick up the navigation mode.
  3. Save/Restore state for itself.

The FrameNavigationService also makes sure that if the app suspends or wakes from a termination then the navigation history is put back in place on the frame( s ) and the relevant ViewModel is driven to save/restore state by driving it through this OnNavigatingTo/OnNavigatingFrom logic.

The VisualStateAwarePage Class

The VisualStateAwarePage is the Page-derived base class for your pages and feels pretty similar to the LayoutAwarePage that comes with the Visual Studio templates (you get that page if you add a Basic Page project item to a Windows Store project).

The page does a number of things;

  1. Watches for view/orientation changes and drives the UI into different visual states depending on those changes. The state names used are taken directly from the ApplicationViewState enum and so will end up being called “FullScreenLandscape”, “Filled”, “Snapped”, “FullScreenPortrait”. These state changes are handled for the page itself along with any controls on the page that have been registered as being “interested” in visual state changes via the StartLayoutUpdates method.
  2. Implements state management for the page (i.e. the View rather than the ViewModel) by providing virtual methods LoadState and SaveState which are passed Dictionary<string,object> for you to save/restore your view’s state.
  3. Provides some convenience methods for forward/back/home navigation and for trapping mouse/keyboard/touch gestures to trigger them.

and that’s pretty much it for the VisualStateAwarePage except that it does one other slightly “odd” (to me) thing. There’s a public static property on this class called GetSessionStateForFrame and that property is of type Func<IFrameFacade, IDictionary<string,object>>.

This is part of (2) above – the state management of the view.

When the page is navigated to or navigated from and wants to restore/save state it needs somewhere to put that state. What it does is to;

  • create a new FrameFacadeAdapter around its Frame (which is has access to because it’s a view which is Page derived).
  • call whatever function is present in the GetSessionStateForFrame property passing it the FrameFacadeAdapter in the hope that it will return an IDictionary<string,object>
  • reach into that dictionary returned, using a page-specific key to attempt to pull out another Dictionary<string,object> which can be used as state storage for the page

    I must admit that I found this functionality a bit “opaque” and it felt a little to me like there’s a missing interface somewhere – it took quite a bit of staring at to try and figure out what’s going on.

    The MvvmAppBase Class

    The MvvmAppBase class is the class that brings all the other pieces together for your app and replaces the standard Application class that provides the base class in the framework and in the standard Visual Studio templates. It derives itself from that Application class and, in my view, simplifies some of the rough edges of that class for you.

    It does quite a lot of work on your behalf and provides lots and lots of places to hook into the default behaviour by overriding methods.

    The starting point for this behaviour is in the override of the OnLaunched method for when the application first runs up. This initialises the root frame which involves a lot of functionality;

    1. Creating the Frame.
    2. Creating a FrameFacadeAdapter to implement IFrameFacade on top of that Frame.
    3. Creating the SessionStateService to provide an implementation of ISessionStateService and storing this in a protected property (SessionStateService of type ISessionStateService) of the MvvmAppBase class itself and registers the main Frame with that service.
    4. Creating the INavigationService by calling a virtual method CreateNavigationService and passing it the IFrameFacade and the ISessionStateService. This is stored in a protected property NavigationService on the MvvmAppBase class itself.
    5. Wires up the static property VisualStateAwarePage such that it has a method to call in order to get the Dictionary<string,object> session storage for a particular frame.
    6. Wires up the SettingsPane such that when it requires settings information for your app it will effectively call the classes own virtual method called GetSettingsCharmActionItems() which you can implement to return your settings options.
    7. Wires up the ViewModelLocator so that, by default, it will call a virtual function Resolve on the MvvmAppBase class in order to create view models.
    8. Calls a virtual method to OnRegisterKnownTypesForSerialization() in case you have any to register with the ISessionStateService.
    9. Sets up handlers for the suspend/resume/terminate state management pieces (and implements those handlers).
    10. Calls a virtual OnInitialize() method via which you can initialise your app’s code.

    That’s quite a lot and you’d need a few overrides in order to get this wired up to look to a container for resolution of these types. Once the application is actually up and running the class also;

    1. Checks the application manifest and if the Search charm is declared there then it grabs hold of the SearchPane and, effectively, wires up the submission of a search query to its own OnSearchApplication virtual method for you to override.

    It’s worth pointing out that the class also overrides the base class OnSearchActivated such that it initialises things and then calls the same OnSearchApplication virtual method thereby giving you one place to implement that functionality.

    Finally, the Suspending event is wired to an OnSuspending handler which will do the right thing around the NavigationService and the SessionService ( using the properties on this class to get hold of those values ) and will also set a simple IsSuspending flag while the operation is in flight.

    Wrapping Up

    At a sketchy level, that’s perhaps most of the classes that Prism provides. I’ve not touched on some of the other services like the ability to display flyouts but that’s my first encounter with the source code. I’ve also not poked so far into the reference application.

    What I think I’d want to do next is build my own “Hello World” using an IoC container like Unity or AutoFac and see how that goes.

    Of course, there’s already a sample in the QuickStarts which does exactly this but I figure I’ll learn more by experimenting with it for myself…