Skip to main content

Design Pattern: Repository

The Repository Pattern is a pattern that defines how to access data in a reusable, isolated fashion. The core concept is to isolate the logic required to call a database, file, or other data source. It can be reused without other layers of the software needing to know the details of how to get that data. An example would be the connection string for a database should be used in 1 location, within a repository, rather than every class that needed data needing a connection string.

The repository is used by calling classes like a collection of data. If I have an employee repository, classes that need an employee can query the employee repository as if all employees were already in an in-memory collection.

var employee = _employeeRepository.FindById(1);

I view the repository as the bottom layer of code.
Code Layers: UI Layer -> Business Logic -> Repository

Isolating data access from the rest of your code has multiple benefits. You can easily write tests by faking or mocking your repository. You do not actually connect to your data source in your tests, instead your repository actually becomes an in-memory collection. It also means that you can setup your data specific for each test and know that it will be in a known good state.

You could also setup caching within your repository which would isolate that logic away from other parts of your system. It also makes it much easier to change how or where your data is stored if you have the need.

A couple of potential drawbacks come to mind with this pattern. First this could create more classes and files within your project. Some would view this as adding complexity, but I feel the benefits would be well worth it. Another possible drawback could be in optimizing your data access. The defaults for your repository might not be the most performant way to query your data. This is likely not going to be a huge issue unless you are working on something that you need to squeeze out every efficiency to make your project successful. In those cases, you could still utilize the repository pattern, but you would need to do extra work to improve performance where needed.

How I would setup a repository in my code

You could create a repository for each and every different data object that you needed, but I have found that most repositories tend to share enough common methods that you can start with a generic repository and build more specific ones as needed.

public interface IRepository<T> where T : IEntity {
    T GetById(int id);
    List<T> GetAll(Expression<Func<T, bool>> where);
    void Delete(T entity); 
    void Add(T entity);
    T Save(T entity);

This interface will likely cover the majority of your needed, but there is always the ability to expand on it when you have more specific queries that you want to reuse.

public interface IEmployeeRepository: IRepository<Employee> {
    List<Employee> GetManagers();
    List<Employee> GetNew();
    List<Employee> GetAllByRole(RoleEnum role);

With this IEmployeeRepository we get all of the methods from IRepository through inheritance and add onto those the methods that most make sense for employees.

One thing I came across while researching the repository pattern was that the repository might not need to have a Save function if you use the Unit of Work Pattern. To better understand why that would be the case, I plan to research the Unit of Work Pattern next.


Post a Comment

Popular posts from this blog

Converting a Large AngularJS Application to TypeScript Part 1

I work on a project that uses AngularJS heavily. Recently we wondered if using a preprocesser like CoffeeScript or TypeScript for our JavaScript would be beneficial. If our team is going to switch languages, we would need to be able to convert existing code over without much pain and we would have to find enough value in switching that it would be worth the conversion. I had read an article that stated that because TypeScript is a SuperSet of JavaScript, you could convert a plain JavaScript file to TypeScript by changing the extension to .ts and not much else would need to change. I wanted to test out this claim, so I took a file that I was familiar with, an Angular Controller, and tried to convert it to TypeScript to see how much effort it would take and then try to figure out where we would benefit from using TypeScript. This is what the controller JavaScript file looked like to start out with: ( function () { 'use strict' ; angular .module( 'app'

Gamify TDD

I like it when things that would not normally be associated with games add concepts from games as a way to incentives you to accomplish things. Why simply go for a run if you can have an app that will track you and give you a gold star if you do better than you did the last time? Why go to the coffee shop that only gives you coffee if the other one will give you points that you can redeem for free drinks eventually? I was recently introduced to C odeSchool , an online training system similar to PluralSight, it has video courses and challenges you can take to prove that you retained what the video taught. CodeSchool also adds badges and tracks to your learning, so as you complete a video and its challenges you get a badge. Complete a collection of courses within a specific discipline and you become a master of that discipline. Some of these incentives are not tangible and really don't mean much in the real world, but they tend to work for me. If I start working towards a large g

Converting a Large AngularJS Application to TypeScript Part 2

In part 1 I was able to take an Angular controller written in JavaScript and convert it to a TypeScript file while doing very little to change the code. In this post I am going to explore transitioning that same controller to actually use the features provided in TypeScript. This is how I left off my controller: declare var angular: any; (function () { 'use strict'; var controller: any = function($scope){ ... } angular .module('app') .controller('controller', controller); controller.$inject = ["$scope"]; })(); While performing the translation from JavaScript to TypeScript, I would make sure at every step that the functionality I expected still worked, so if anything I did broke the system I would change it back and try again with another approach. Also if something seemed like it worked too easily, I would break it on purpose to make sure I wasn't getting a false result through browser caching a previously working