Click here to Skip to main content
15,867,308 members
Articles / Hosted Services / Azure

Repository Pattern with Windows Azure Mobile Services for Windows Phone app and Windows Store app

Rate me:
Please Sign up or sign in to vote.
4.47/5 (4 votes)
8 Apr 2013CPOL2 min read 16.9K   10   3
Repository Pattern with Windows Azure Mobile Services for Windows Phone app and Windows Store app.

Introduction

Windows Azure Mobile Services is a fantastic tool and very easy to use. In this post, I will show you how to use the repository pattern with the Mobile Services SDK.

If you are familiar with Entity Framework, this pattern is used in many projects and samples. You can find a definition here: http://msdn.microsoft.com/en-us/library/ff649690.aspx or here http://www.codeproject.com/Articles/526874/Repositorypluspattern-2cplusdoneplusright.

In this sample, we will use the portable library to share our data access layer with Windows Phone, Windows 8 and .NET apps.

At the end, we will be able to inject our repository in our services / view models and to make our code testable.

Using the Code

At first, we will create three projects with the template Portable Class Library:

  • MyNamespace.Models
  • MyNamespace.Data
  • MyNamespace.Data.MobileService 

 MyNamespace.Models

This project contains our data model. It’s just a simple class which describes our entities:

C#
public class ToDoItem
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
} 

MyNamespace.Data

This project contains the contracts (interfaces) for the repositories.

First, we will create the base interface, called IRepository. It contains all CRUD base operations. 

C#
public interface IRepository<T>
{
    Task<IEnumerable<T>> GetAllAsync();
    Task CreateAsync(T entity);
    Task UpdateAsync(T entity);
    Task RemoveAsync(T entity);
}

As explained, the repository pattern needs a repository interface for each data model. Here, the contract for the model ToDoItem

C#
public interface IToDoItemRepository : IRepository<ToDoItem>
{

} 

It’s in the interface that we will add customs queries, if needed.

MyNamespace.Data.MobileService

The project contains the implementation for Mobile Services of our interfaces.

First, you have to add the mobile services reference to you project with nuget. I recommend to use the latest prerelease version (http://nuget.org/packages/WindowsAzure.MobileServices/0.3.2-alpha).

We will create a base repository with all base operations for the CRUD. 

C#
public abstract class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected IMobileServiceClient MobileServiceClient { get; set; }

    protected BaseRepository(IMobileServiceClient mobileServiceClient)
    {
        if (mobileServiceClient == null) throw new ArgumentNullException("mobileServiceClient");
        this.MobileServiceClient = mobileServiceClient;
    }

    protected virtual IMobileServiceTable<TEntity> GetTable()
    {
        return this.MobileServiceClient.GetTable<TEntity>();
    }

    public virtual Task<IEnumerable<TEntity>> GetAllAsync()
    {
        return GetTable().ToEnumerableAsync();
    }
    public virtual Task CreateAsync(TEntity entity)
    {
        return GetTable().InsertAsync(entity);
    }

    public virtual Task<IEnumerable<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate)
    {
        return GetTable().Where(predicate).ToEnumerableAsync();
    }

    public virtual Task UpdateAsync(TEntity entity)
    {
        return GetTable().UpdateAsync(entity);
    }
    public virtual Task RemoveAsync(TEntity entity)
    {
        return GetTable().DeleteAsync(entity);
    }
} 

Now, we are ready to write the implementation of IToDoItemRepository.

C#
 public class ToDoItemRepository : BaseRepository<ToDoItem>, IToDoItemRepository
{
    public ToDoItemRepository(IMobileServiceClient mobileServiceClient) : base(mobileServiceClient)
    {
    }
} 

This implementation is the base. If you have custom query, you can simply add your methods in the repository.

How to Use My Repository?

Our repository pattern is now implemented, we can easily use it in a Windows Phone project.

In my WP project, I really enjoy using Caliburn.Micro and Autofac. You can add the nuget reference to Caliburn.Autofac. You can now register the repositories and the MobileServiceClient.

C#
public class Bootstrapper : AutofacBootstrapper
{
    protected override void ConfigureContainer(ContainerBuilder builder)
    {
        // register MobileServiceClient
        builder.RegisterType<MobileServiceClient>()
            .AsImplementedInterfaces()
            .WithParameter("applicationUrl", "MyAppUrl")
            .WithParameter("applicationKey", "MyAppKey")
            .InstancePerLifetimeScope();

        // register ToDoItemRepository
        builder.RegisterType<ToDoItemRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();

        base.ConfigureContainer(builder);
    }
}

Your repositories are now registered, you can call them in the ViewModels.

C#
public class MainViewModel : Screen
{
    private readonly IToDoItemRepository _toDoItemRepository;
    private List<ToDoItem> _toDoItems;

    public MainViewModel(IToDoItemRepository toDoItemRepository)
    {
        _toDoItemRepository = toDoItemRepository;
    }

    protected override void OnActivate()
    {
        LoadData();
    }

    private async void LoadData()
    {
        // create an entry for the test
        await _toDoItemRepository.CreateAsync(new ToDoItem {Title = "my title", 
                       Description = "my description"});

        // load all data
        ToDoItems = new List<ToDoItem>(await _toDoItemRepository.GetAllAsync());
    }

    public List<ToDoItem> ToDoItems
    {
        get { return _toDoItems; }
        set
        {
            if (Equals(value, _toDoItems)) return;
            _toDoItems = value;
            NotifyOfPropertyChange(() => ToDoItems);
        }
    }
} 

Conclusion

And voila, the repository pattern with Azure Mobile Services is now implemented. Thanks to the portable library, our data access layer is fully shareable with Win8 / .NET apps.

In a future post, we will see how to create unit tests to test the view models.

Enjoy!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
France France
Specialized in .net technologies for many years, I am a technology fan in both asp.net and wpf/silverlight, using c# and .NET 4.

Comments and Discussions

 
QuestionRepository Pattern with Windows Azure Mobile Services for android Pin
kumar kundan26-Aug-15 9:14
kumar kundan26-Aug-15 9:14 
GeneralMy vote of 5 Pin
Jhonathan Izquierdo24-Jun-13 10:17
Jhonathan Izquierdo24-Jun-13 10:17 
GeneralMy vote of 5 Pin
leandroshan11-Apr-13 5:13
leandroshan11-Apr-13 5:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.