A Silverlight application by its nature is a distributed app with a front-end on the client and a web service to provide connectivity to the data store.
Application Diagram
In order to decouple dependencies between components, I use dependency injection. All components consumed by other components define a strong contract through an interface, making them replaceable and making unit testing simpler. Since the front-end connection with the business logic is handled declaratively, no contract is required.
Sample Application
For our working example, we have a straightforward requirement:
- Display a list of users
- Allow adding, updating and deletion of users
So we are defining a simple CRUD operation on an entity. The following class diagram describes the different components needed to implement this using the Model-View-ViewModel design pattern.
Class Diagram
The view binds to the data model for interaction with the entities. To handle user interaction, we will be binding to a component called "ViewModelAction" which encapsulates event handling and availability, similar to WPF commands. The components are relatively lightweight and are focused on streamlining the binding process. This allows the view contain absolutely no code.
The common functionality for these components is defined in a central library that could be re-used for other applications. The View, Model, ViewModel and ViewModelAction base classes are all derived from a abstract class called Component which mainly implements property change notification through the INotifyPropertyChanged interface.
Gotcha
One of the obstacles I ran into with declarative binding is that the visual designer attempt to instantiate all objects. In the case of the model, this was bad as Visual Studio was attempting to connect to the web service and failing. I added an "IsDesignMode" flag to component to wrap calls to external resources in my components. This is the same solution to a similar problem in ASP.Net.
Up Next
I'm going to take a top down approach to subsequent blogs to keep my non-developer audience interested longer. I will show how the view is defined in XAML, followed by the ViewModel (with kung fu action) and lastly the Model.