WCF RIA Services DomainContext Abstraction Strategies–Say That 10 Times!

Posted by dwahlin on ASP.net Weblogs See other posts from ASP.net Weblogs or by dwahlin
Published on Tue, 21 Dec 2010 02:45:30 GMT Indexed on 2010/12/21 5:01 UTC
Read the original article Hit count: 635

Filed under:
|
|
|

The DomainContext available with WCF RIA Services provides a lot of functionality that can help track object state and handle making calls from a Silverlight client to a DomainService. One of the questions I get quite often in our Silverlight training classes (and see often in various forums and other areas) is how the DomainContext can be abstracted out of ViewModel classes when using the MVVM pattern in Silverlight applications. It’s not something that’s super obvious at first especially if you don’t work with delegates a lot, but it can definitely be done. There are various techniques and strategies that can be used but I thought I’d share some of the core techniques I find useful.

To start, let’s assume you have the following ViewModel class (this is from my Silverlight Firestarter talk available to watch online here if you’re interested in getting started with WCF RIA Services):

public class AdminViewModel : ViewModelBase
{
    BookClubContext _Context = new BookClubContext();

    public AdminViewModel()
    {
        if (!DesignerProperties.IsInDesignTool)
        {
            LoadBooks();
        }
    }

    private void LoadBooks()
    {
        _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, null);
    }


    private void LoadBooksCallback(LoadOperation<Book> books)
    {
        Books = new ObservableCollection<Book>(books.Entities);
    }
}

Notice that BookClubContext is being used directly in the ViewModel class. There’s nothing wrong with that of course, but if other ViewModel objects need to load books then code would be duplicated across classes. Plus, the ViewModel has direct knowledge of how to load data and I like to make it more loosely-coupled. To do this I create what I call a “Service Agent” class. This class is responsible for getting data from the DomainService and returning it to a ViewModel. It only knows how to get and return data but doesn’t know how data should be stored and isn’t used with data binding operations.

An example of a simple ServiceAgent class is shown next. Notice that I’m using the Action<T> delegate to handle callbacks from the ServiceAgent to the ViewModel object. Because LoadBooks accepts an Action<ObservableCollection<Book>>, the callback method in the ViewModel must accept ObservableCollection<Book> as a parameter. The callback is initiated by calling the Invoke method exposed by Action<T>:

public class ServiceAgent
{

    BookClubContext _Context = new BookClubContext();

    public void LoadBooks(Action<ObservableCollection<Book>> callback)
    {
        _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, callback);
    }

    public void LoadBooksCallback(LoadOperation<Book> lo)
    {
        //Check for errors of course...keeping this brief
        var books = new ObservableCollection<Book>(lo.Entities);
        var action = (Action<ObservableCollection<Book>>)lo.UserState;
        action.Invoke(books);
    }
}

This can be simplified by taking advantage of lambda expressions. Notice that in the following code I don’t have a separate callback method and don’t have to worry about passing any user state or casting any user state (the user state is the 3rd parameter in the _Context.Load method call shown above).


public class ServiceAgent
{

    BookClubContext _Context = new BookClubContext();

    public void LoadBooks(Action<ObservableCollection<Book>> callback)
    {
        _Context.Load(_Context.GetBooksQuery(), (lo) =>
        {
            var books = new ObservableCollection<Book>(lo.Entities);
            callback.Invoke(books);
        }, null);
    }
}

A ViewModel class can then call into the ServiceAgent to retrieve books yet never know anything about the DomainContext object or even know how data is loaded behind the scenes:

public class AdminViewModel : ViewModelBase
{
    ServiceAgent _ServiceAgent = new ServiceAgent();

    public AdminViewModel()
    {
        if (!DesignerProperties.IsInDesignTool)
        {
            LoadBooks();
        }
    }

    private void LoadBooks()
    {
        _ServiceAgent.LoadBooks(LoadBooksCallback);
    }


    private void LoadBooksCallback(ObservableCollection<Book> books)
    {
         Books = books
    }
}

You could also handle the LoadBooksCallback method using a lambda if you wanted to minimize code just like I did earlier with the LoadBooks method in the ServiceAgent class.  If you’re into Dependency Injection (DI), you could create an interface for the ServiceAgent type, reference it in the ViewModel and then inject in the object to use at runtime. There are certainly other techniques and strategies that can be used, but the code shown here provides an introductory look at the topic that should help get you started abstracting the DomainContext out of your ViewModel classes when using WCF RIA Services in Silverlight applications.

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about wcf