wolfgang ziegler


„make stuff and blog about it“

The ASP.NET MVC Repository Pattern

June 17, 2012

The basic principle and design pattern behind the MVC architecture is SoC (Separation of Concerns). This design pattern states that different application layers and components should be clearly isolated and as independent from each other as possible.

With the Model-View-Controller (MVC) concept, SoC works pretty well out of the box, because of the clear distinction between UI, data models and controller logic. One area, where the SoC pattern can still be improved, is the model layer, where the data model classes should just be responsible for providing data to the views but not for retrieval, manipulation and storage of data. This is where the repository pattern comes into play.

Repositories are abstract “containers” for data models and the abstraction they provide is about the actual data source. If models are accessed through a repository the user does not need to care about whether the actual data is stored in a database, the file system or e.g. retrieved through another web service.

The typical way repositories are implemented is through interfaces, because this provides the ability to create different implementations for the actual data source for testing, staging and production scenarios. Additionally, this plays together very well with dependency injection frameworks.

Let’s look at an example right now:

1.) We start with a model class called Person.

public class Person
{
  public string FirstName { set; get; }
  public string LastName { set; get; }
}

2.) For this class, we create a repository called IPeopleRepository.

public interface IPeopleRepository
{
  IQueryable<Person> People { get; }
}

This class provides an IQueryable collection of Person objects. By using the IQueryable collection class, we can use the full set of LINQ operations on the returned collections and at the same time the actual data source is abstracted.

3.) An implementation of the repository for testing purposes could look like this.

public class FakePeopleRepository : IPeopleRepository
{
  private IQueryable<Person> _people = new List<Person>
  {
    new Person() { FirstName = "Wolfgang", LastName = "Ziegler" },
    new Person() { FirstName = "John", LastName = "Doe" },
  }.AsQueryable();

  public IQueryable<Person> People
  {
    get { return _people; }
  }
}

4.) The implementation of an ASP.NET MVC controller class leveraging the repository will now look like this.

public class PersonController : Controller
  {
    private IPeopleRepository _repository = new FakePeopleRepsitory();

    public ActionResult Index()
    {
      return View(_repository.People);
    }
  }

Any time the actual implementation of the repository can be changed now to use e.g. a database. The the rest of the application this happens in a fully transparent way.

5.) And so we reached our goal – true separation of concerns.