Architecting Silverlight LOB applications (Part 5) – Modules and UI composition

In this fifth post and the next ones I’m going to write about client development and how to create a modular and composite silverlight application. In this post I’ll focus on UI composition.

When building composite LOB silverlight apps you should be aware that modularity is an important requirement. As a developer it should be easier for you to mantain your code and add new features to your application without having to change the rest, plus your application’s XAP file doesn’t grow bigger. Every module is a separate XAP file, that can be downloaded on demand, depending on the user’s intent to use a certain functionallity.

Below is one possible architecture to achieve what we need.


Continue reading


Architecting Silverlight LOB applications (Part 3) – DomainServices and Repository

Hello again,

In the previous post I described an overview of an architecture that could be used when developing silverlight modular apps. In this post I’ll start with a simple business domain model and create a domain layer around that model.

In this example our app will be a web application for a company that sells products and that can be used by its customers to fulfill orders and its employees to process them. These orders have details which consist of products and quantities. Each product can have a product category. When a customer submits an order fulfillment, an employee of the company may process that order to prepare the items for shipping.

The company has a few departments, and each employee belongs to a department. This means that employees from the Sales department will be to process orders; employees from the Human Resources department will be able to recruit new employees; and employees from the Financial Department will be able to watch some charts and print reports with statistics of how sales are evolving as time goes by, sales reports, etc.

Continue reading

Architecting Silverlight LOB applications (Part 1) – Concepts and technologies

In this first part of the series I’ll focus on some open source projects in Microsoft’s Patterns & Practices and other technologies that are available and can help us achieve our goal.

First we have PRISM (Composite Application Guidance for WPF and Silverlight). PRISM is composed of a guidance and a set of libraries that are designed to help you more easily build modular WPF and Silverlight apps. It also has built-in components that let you take advantage of some known patterns like MVVM, Event Aggregator and Dependency Injection. There are others but I’ll focus on these three because I find them to be the most useful.


PRISM applies to client development. I think the best feature PRISM provides is the ability to specify your application modules (XAPs in Silverlight) as a catalog and load them on demand. We’ll explore this in detail in other parts of this series when we create a module catalog to be used within the application.

Dependency injection (a specific usage of the Inversion of Control concept) is a prime technique for building loosely coupled applications because it provides ways to handle dependencies between objects. It helps you build testable code because you can easily switch concrete implementations which your objects depend on. PRISM is built using this design principle and it uses the Unity container, which implements the DI technique. PRISM also lets you use other DI containers but I’ll focus on Unity since I haven’t enough experience with others.

This pattern can be applied in both client and server development.

I didn’t find a nice and simple figure about Dependency Injection so I’ll link to this post where I’ve used this technique in a WCF Service (OrderService) which used an IOrderRepository implemented by the OrderRepository class which had dependencies being injected in its constructor.

The MVVM pattern is becoming the alpha and the omega when building WPF and Silverlight apps. It helps you separate concerns when designing your presentation layer and if it is well thought you can create a great set of reusable code for your application and even reuse it for other applications.


With MVVM you basically think of your view as a set of classes and properties and not as a set of UI controls. This allows you to easily switch your UI while keeping the same logic that it is bound to, and at the same time enables testability. Plus it allows you to reuse a set of UI logic in lots of views with less effort. This pattern is applied to client development.

The Event Aggregator pattern allows you to build your app with an Event Driven Architecture where components communicate with each other in a decoupled manner. It provides a way to publish and subscribe to events without knowing who is subscribing or who is publishing. The only thing you need to know is the event you are publishing or subscribing and how to react to that event. Usually modules do not depend on each other and using events as contracts to communicate between them is a good approach. This pattern applies to client development.

Next we’ll focus on server development.

Client-server communication in Silverlight has been enforced and recommended to use web services. Since we are building LOB applications it makes sense to use services that are good to deal with data. WCF services sure are good but are they ideal? What’s the cost of maintaining a complete service layer that lets us expose CRUD operations on our data and also provides us the ability to do other queries (like get products by productType), or other business operations? How many times have we done this? And how many times have we done this for different applications? How about validation of the data on the server and client side? How about proxy generation? How about the amount of data sent to the wire just to change a DateTime value on the database?

We all know Visual Studio’s generated code is ugly as hell and maintaining client-side complete service agents can be troublesome, because you usually need to keep it synchronized with your service contract. In Silverlight it is slightly more complicated to share an assembly with service and data contracts than WPF, because of type incompatibilities. Also we usually like our client-side data contracts to implement INotifyPropertyChanged and use ObservableCollections so we take advantage of data binding but at the server we really do not care about this.

WCF RIA Services aims to solve all these problems and many others.. I’ll skip the “all the things RIA Services can do part”, and point you to the right place if you still don’t know. The most important features we’ll explore are query composition, data validation, change tracking, unit of work, among others.


I’ve been using RIA Services for the last 7 months and one thing I find very useful is that the way you communicate either with the server and with your model (at the client side) is through a very well defined API which makes it easy to create very generic code that can be used to create reusable viewmodels. This is especially useful when you have multiple persons working in the same project and you want to ensure that everyone will code the same way (I will definitely explore this in later posts).

WCF RIA Services current release is the RC2, it has a go live license, so we’re good to go.

This doesn’t mean you shouldn’t use WCF as well. There are cases where WCF RIA Services isn’t well suited to work for. For example, file uploading or downloading. In this situation it’s preferable that you create a WCF Service or an HttpHandler to deal with this particular case.

For our data layer the best options nowadays are still NHibernate (using Linq to NHibernate) or Entity Framework. Nevertheless, we should encapsulate our data access through repository objects and do not use our data access technology directly in our services. I’ve got a very simple post that talks exactly about this. In this case, we can use any or both. RIA Services generates code on the client based on reflection and other metadata that is applied in our server side entities. If you use Entity Framework with RIA Services it already has a specific metadata provider that is able to understand relationships between entities and generate them correctly in the client. If you wish to use NHibernate you will have to specify additional metadata in your entities. For simplicity I’ll use Entity Framework. There are other resources on the web that explains how to use NHibernate.

Last but not least, I’d like to talk about MEF. MEF stands for Managed Extensibility Framework, has been shipped with .NET 4 (SL4 also) and is designed to help us compose our apps in a decoupled way much easier than using an IoC container for dependency injection. You simply annotate your classes with Import/Export attributes and MEF will resolve dependencies between objects for you. Of course there’s more we can do. You can provide metadata when exporting an object and import only objects that follow some criteria. MEF can be used to download XAP’s when an Import must be satisfied and the exported object is in another XAP, which helps building modular apps. It is said that the new Prism version will use MEF for its modularity features, which makes it even more interesting.

In the next post I will start with a simple business scenario and follow a top-down approach by designing an architecture built upon these technologies. I haven’t had much time lately but I’m trying to catch up so see you soon!

Architecting Silverlight LOB applications

This post is an introduction to a series of posts that I will be doing about how we can architect an enterprise data-centric Silverlight application. While Silverlight is a powerful platform to create great interactive user experiences for Web, Desktop (and now) Mobile, it is also Microsoft’s best bet to create a multi-platform, cross-browser technology.

A lot of people think of Silverlight as just another Adobe Flash rival because of the RIA aspects both technologies offer and the strong multimedia support that Silverlight has. While this is true, we can get much more from Silverlight if we think of it as good technology for the software industry in Information Technologies. IT projects are all about manipulation, visualization and understanding data.

Silverlight, which is a subset of WPF (excellent to deal with data through data binding) and still a .NET application, when combined with today’s most popular patterns and some key technologies for software engineering, can be a very productive, straight-forward, reliable and successful technology to build this kind of applications, and at the same time, provide great UX.

In this series of posts I will try to cover key aspects when you are architecting an application that can start small, are meant to last for years and over time evolve into a bigger application due to new requirements and be developed by multiple teams without resulting in a big mess of code that no one ever wants to touch.

Such applications often are built using the following principles:

  • Separation of Concerns
    • The most important principle. Ability to divide and conquer by creating layers in your application that are meant to deal with a specific problem, task or functionality, thus reducing complexity. The rest of the principles are all based on this one.
  • Loosely coupling
    • Ability to create multiple components that can work together but do not depend on each other.
  • Flexibility
    • Ability to respond to future changes, either by completely switching the underlying technology or business needs.
  • Extensibility
    • Ability to create new functionality by extending or reusing existing one.
  • Modularity
    • Ability to create well defined (cohesion) independent business areas in your application that can be evolved separately, integrate with each other and even be deployed separately.
  • Testability
    • Ability to avoid/prevent unexpected bugs by changes or new functionality you make, by testing your application’s logic, behavior or dependencies.
  • Maintainable
    • Ability to quickly find the code you need to change, understand it and change it, even if the one who wrote it in the first place is not around anymore (happens frequently).
  • Reutilization
    • Ability to reduce code by creating components that will be reused by other components that require a specific functionality.
  • UI Independence
    • Ability to switch your presentation controls without breaking neither your presentation logic nor your application logic.
  • Localization
    • Ability to target multiple languages, thus increasing your range of customers.

I’m thinking in starting with an overall architecture, choose the right technologies, build a small application on top of it and then keep composing it. I’ll start with .NET 3.5 and later on move to .NET 4.

See you soon!

Managing the Entity Framework ObjectContext instance lifetime in WCF and sharing it among repositories

As I pointed out in a previous post about using the Repository pattern in EF and WCF, it’s a bad practice when service operations manage the ObjectContext instance lifetime and have dependencies on it.

In this post I’m going to show you how to share the same ObjectContext among repositories as long as the service is activated (either PerCall or PerSession) and have the service totally agnostic of it.

First lets introduce two concepts:

public interface IDbContext : IDisposable
    object Context { get; }

public interface IDbContextManager
    IDbContext GetDbContext();

The IDbContext interface can be used as a wrapper for the ObjectContext or even NHibernate’s ISession. The IDbContextManager will be used by the repositories to get an IDbContext instance.

To simplify things we can extend our existing ObjectContext class using a partial class that implements the IDbContext interface. In this case, since I’m using the same example as the previous post it should look like this:

public partial class MFEntitiesContainer : IDbContext
    public object Context
        get { return this; }

Lets see how the refactored EntityRepository class looks like:

public class EntityRepository<TEntity> : IRepository<TEntity>
    where TEntity : EntityObject, new()
    public EntityRepository(IDbContextManager manager)

    private void SetContext(IDbContext ctx)
        this.ObjectContext = ctx.Context as ObjectContext;

    //.. same implementation as the previous post

So now we can use our repositories without having to worry how to give them an ObjectContext anymore. We simply have to supply an implementation of IDbContextManager. In this case, I’m going to implement a DbContextManager that will return the same IDbContext instance while the wcf service is activated in order to reuse it among repositories.

Continue reading

Encapsulating Entity access in EntityFramework by using the Repository pattern

EntityFramework provides a very easy way to query your entities and thus the database but it creates a very strong dependency between the calling code and the data access layer(EF in this case).

The Repository pattern allows you to encapsulate any entity access logic and also to decouple your business logic layer from your data access layer, in other words, enables separation of concerns, plus it makes unit testing a lot easier.

Consider the following entity data model:


And a WCF Service that exposes Orders and its aggregated OrderDetails:

public class OrderService : IOrderService
    private MFEntitiesContainer _context = new MFEntitiesContainer();

    public IEnumerable<Order> ListOrders()
        return _context.OrderSet.Include("OrderDetails")
                                .Where(o => o.Customer.Active);

    public IEnumerable<Order> ListOrdersByCustomer(int customerId)
        return _context.OrderSet.Include("OrderDetails")
                                .Where(o => o.Customer.Active && o.Customer.Id == customerId);

Lets see how we can refactor the OrderService to use the Repository pattern instead of querying the EF’s ObjectContext.

Continue reading