Silverlight, M-V-VM ... and IoC - part 3

It’s time to go on with this series, at this point we know the basic principles of MVVM and we have a set of base classes and interfaces we can use. We need to put it in action and see how we can implement the View and the ViewModel and how we can tie them together with an IoC container.

Note: all the samples I post here directly derive for the ‘test project’ I use for all my Silverlight based workshops and experiments. I have published it on Codeplex and I’m moving to it from my private Subversion...I’ll try to reconstruct the history of the check-ins following the same major step stones I had in my private repository.

You can find the project at this link: http://dnmmusicstoresl.codeplex.com/. The code presented here refers to the Changeset 41379, this was a direct porting from a Silverlight 3 project (no RIA services, no custom behavior nor commanding engine was used at this stage).

The scenario: we are building a back-office for a Music Store Shop, they have a list of albums in their store and we want to build a form that allow us to perform simple queries on the data, we give for granted the ‘server-side’ of the whole thing (we have a WCF web service that we can reference and that will expose a SearchAlbum(string) function that will filter the data).

The goal: build a ViewModel that expose the data and some functions the View can bind to and use, buildup a View that is able to use the ViewModel, then configure our IoC container to be able to resolve the object tree we need to show the form to the user.

The model: at this stage I kept the things simple (no new technologies like RIA services yet): ‘server side’ I have a simple AlbumSummary class that will contain all the information we need to display, ‘client side’ we make a reference to the web service and we use the proxy classes that it will generated for us.

/// <summary>
/// class returned by the search it contains some informations about the albums
/// </summary>
[DataContract]
public class AlbumSummary : DomainObject<int>
{
	[DataMember]
	public virtual string Title { get; set; }
	
	[DataMember]
	public virtual string Author { get; set; }
	
	[DataMember]
	public virtual string Label { get; set; }
	
	[DataMember]
	public virtual string Genre { get; set; }
	
	[DataMember]
	public virtual DateTime PublicationDate { get; set; }

Castle Windsor – Silverlight 4 binaries

Working on solutions based on IoC systems and for our recent DotNetMarche workshop, in which we shown how you can architect a solution based on these systems and some advantages you can have using AOP techniques, I wanted to update the actual Castle Windsor binaries I use in my Silverlight solutions.

The version I used in the past was tied to Silverlight 3, but with Silverlight 4 going RTM I thought that an update was needed; given also the tremendous job the guys that maintain and develop the solution are doing to add new features, improve performances and narrow down the number of assemblies the core solution have.

I downloaded the solution and tried to compile it for Silverlight 4, unfortunately during the moving from Subversion to Git and during the solution refactoring some things were left behind/stopped working (the refactoring is still in progress) and the project compiles well for .net 3.5 but not for Silverlight: the relative solutions got removed from the project.

So I’ve then decided to checkout the actual trunk code, and brutally rebuild the solution files using Visual Studio 2010 and recompile them by myself, it wasn’t that hard after the refactoring they made. Exchanging a couple of mails with Krzysztof Koźmic on the topic, he suggested me to create a fork on Github and also informed me that Julian Birch was working on a solution to convert and adapt the project to enable Silverlight compilation (however Julian is currently working only on Castle.Core, while I also needed Windsor for the IoC container).

After fighting against Git a bit to make it work on my machine, I was able to have it up and running and commit the files to my forks, here are some links for you:

Castle Windsor: http://github.com/castleproject

My forks: http://github.com/AGiorgetti

The compiled binaries:

Note: actually I’ve got no unit tests that runs on the Silverlight solution, I took those binaries and used them in my current projects without any issue (but I’m not using any of the more advanced Castle Windsor capabilities, just normal plain IoC/DI and AOP through interceptors). Julian’s solution have a version of NUnit (the unit test framewrok used in Castle) that works with Silverlight, when I’ve time I’ll look into it or maybe I’ll see how hard is to port the tests into the standard Silverlight test framework.

Related Content


Silverlight, M-V-VM … and IoC – part 2

In the previous post I’ve presented a very fast introduction of what MVVM is and I’ve defined the two basic interfaces for the view and the viewmodel; I’m not going to implement a ‘pure’ version of the pattern itself because I consider a pattern just a guideline solution to a problem, not something that have to lock me in a cage.

It’s now time to write some infrastructural code that will work together with the two afore mentioned interfaces, we’ve already said that the ViewModel should expose bindable properties that the View will use to display the data.

To obtain that you can use (or combine) two techniques: derive a basic class for your ViewModel from the DependencyObject class and use the dependency and attached property that the framework already provide, or you can choose a more lightweight approach and implement the INotifyPropertyChanged interface in your base class.

Also remember you will have to deal with asynchronous operations too, so maybe the data on your bindable properties can be updated in a background thread (and changing a bound property from there can result in an AccessViolationException…because you cannot alter anything that involves the UI or the control status from there: WPF and Silverlight objects belong to the thread on which they are created and cannot be accessed by any other thread directly).

To keep things simple in my current implementation I’ve followed the second approach, so my infrastructure code base when dealing with the MVVM pattern and asynchronous operations looks like this:

MVVM_Scheme2

Let’s take a look at the classes and their purposes:

Model: the base class of the whole infrastructure, it can be used to derive Domain Model/DTO and ViewModel classes, it just implement the IDisposable and the INotifyPropertyChanged interfaces to enable the derived class for effective data binding. To allow you to change the bound properties even in background threads internally it uses the UiDispatcher utility class.

/// <summary>
/// base class for Domain Model, DTO and ViewModel classes
/// </summary>
public class Model : INotifyPropertyChanged, IDisposable
{
	/// <summary>
	/// a dictionary to cache property changed event args generated for each property
	/// </summary>
	private static readonly Dictionary<string, PropertyChangedEventArgs> _eventArgsMap =
		 new Dictionary<string, PropertyChangedEventArgs>();

Silverlight, M-V-VM ... and IoC - part 1

Speaking of my previous post about build and IoC-enabled Silverlight Navigation framework a couple of friends of mine asked me mode details about how I implemented the MVVM pattern for a line of business application.

Model-View-ViewModel is a very simple pattern and suits very when developing with WPF and (now) Silverlight. In its ‘pure form’ the biggest advantage of this pattern is that you can develop your application engine and your application UI completely decoupled from each others and this makes your core engine completely testable.

The principle is very simple and you have lot of resources on the web to look for, but the basic idea is this:

MVVM_SchemeThe Model describes your application Domain, it’s a series of classes that represent your data and come from a wide range of sources (local data, databases, web services, etc..whatever you like).

The View is your application front-end, it’s the interactive portion of your application and defines the UX and the look and feel of your work.

The ViewModel acts like a mediator between the two: here you can shape and tailor the data you want to present to the user and you expose a series of functions the UI can use to interact with the data and the services. In a ‘not pure’ implementation the ViewModel can also drive the UI according to some background processing you can do on the data.

The interaction between the View and the ViewModel must happen using the less code-behind you can, ideally you should only use that the Framework already offers to you: Databinding and Commanding.

But we have also another actor to take into account: the IoC container...we plan to use an IoC container if we want to build a very modular application. The container can be whatever you like, there are lots of different implementation around: Unity, Castle Windsor, NInject, Autofac...etc...they differ in some of their advanced features, but they all offer the basic functionalities we need, so you can also ‘hide’ the actual container you use behind a wrapping interface if you need to swap it also.

Given the previous approach and the intrinsic benefit of the pattern I want to be able to switch some of the Views or some of the ViewModels based on the configuration of the container.

This is a big advantage in terms of testability and when you aren’t the only one working on the application, for example you can buildup a series of mockups of your ViewModels and configure an application that the UI designer/ UX experts can use to develop the front-end. You can also use this technique to deliver a quick and dirty ‘preview’ of some of the features your application will have.

For this reason I like to think about the contracts (interfaces) these components will expose first, it also will help me assign a specific role of them, I like to keep things simple (if I can), so I’ve started with something like this:

public interface IView
{
	IViewModel ViewModel { get; set; }
}

Silverlight Navigation Framework: resolve the pages using an IoC container

Silverlight 3 introduced to us a good navigation framework: you could combine Frames and UriMapper objects to change portion of your page (or the entire page) on the fly allowing you to navigate to different section of your application. There are plenty of resources available on the topic, just make a search for them.

Silverlight 4 further improved the model allowing us to easily customize portion of this framework too: we can for example change the way a new object (page) is loaded into a Frame implementing our own version of the INavigationContentLoader interface and assigning it to the ContentLoader property of the Frame object.

I won’t hide the fact I’m a big fun of writing ‘modular’ applications, so I tend to separate everything in components and use interfaces contracts for each module, an IoC container works very well in this scenario because you can think of it just like your service provider or an application entry point provider.

Being able to combine an IoC container with the Navigation Framework and the UriMapper will give us great flexibility, because we can easily swap part of the application just reconfiguring the objects inside the container, making the writing of a modular Silverlight application a - cough cough -breeze.

What I want to obtain is this:

<navigation:Frame x:Name="ContentFrame" 
                  Source="/Home" 
                  Navigated="ContentFrame_Navigated" 
                  NavigationFailed="ContentFrame_NavigationFailed">
    <navigation:Frame.ContentLoader>
        <helpers:IocNavigationContentLoader />
    </navigation:Frame.ContentLoader>
    <navigation:Frame.UriMapper>
        <uriMapper:UriMapper>
            <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
            <uriMapper:UriMapping Uri="/Search/{query}" MappedUri="Search?q={query}"/>
            <uriMapper:UriMapping Uri="/Album/{id}" MappedUri="Album?id={id}"/>
            <uriMapper:UriMapping Uri="/Search" MappedUri="Search"/>
            <uriMapper:UriMapping Uri="/Album" MappedUri="Album"/>
            <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
        </uriMapper:UriMapper>
    </navigation:Frame.UriMapper>
</navigation:Frame>

Ready for the 14th DotNetMarche Workshop? IoC, DI, AOP and related techniques = lot of fun for all

On April 16 in Italy at Castelfidardo (Marche) it will take place the next DotNetMarche workshop, based on the requests and the feedback we had on our previous works, we’ve decided to focus on showing some techniques and ‘best practice’ you can use while developing an application using IoC / DI / AOP.

we’ll have 4 sessions for an afternoon of fun!

  • Stefano Leli - will introduce us to some of the basic concepts of using (and why using) an IoC/DI container to modularize your applications.
  • Andrea Balducci - will show us some of the most used libraries (Castle Windsor, Unity,...) and other advanced features these frameworks offer.
  • Giorgetti Alessandro (me :D) - will bring everything ‘live’ in a Silverlight 4 application; we’ll talk about the (in)famous service locator pattern and we’ll see some application examples: I took the demo application we’ve developed and used in the past workshops and refactored it to use a modular approach with an MVVM pattern for the UI...everything is configured and resolved through the IoC container.
  • Gian Maria Ricci - will introduce some AOP techniques to improve the application and clean-up the design a bit.

At the end of the workshop we’ll have the usual Q&A session (and the even more usual dinner after :D)...don’t loose your chance to embarrass us!

For registration and more info head to our community website: www.dotnetmarche.org.

Related Content