Repository Pattern Explained Simply

Repository Pattern is likely the only design pattern you will implement as software developer. %99 of software design patterns are very rarely implemented, but the repository pattern is something you will see everyday.

First, let’s just see a Repository Pattern and what it is:

using PokemonReviewApp.Data;
using PokemonReviewApp.Dto;
using PokemonReviewApp.Interfaces;
using PokemonReviewApp.Models;

namespace PokemonReviewApp.Repository
{
    public class PokemonRepository : IPokemonRepository
    {
        private readonly DataContext _context;

        public PokemonRepository(DataContext context)
        {
            _context = context;
        }


        public Pokemon GetPokemon(int id)
        {
            return _context.Pokemon.Where(p => p.Id == id).FirstOrDefault();
        }


        public ICollection<Pokemon> GetPokemons()
        {
            return _context.Pokemon.OrderBy(p => p.Id).ToList();
        }

    }
}

All this code does is get things from a database! That is a Repository Pattern in a nutshell.

A Repository Pattern is simply a class that abstracts away database code. We could easily place all this code directly into our controllers, but as our app grows this will start to become a total mess.

Step-By-Step Breakdown

You may be thinking to yourself, “Well how does it actually work…break it down”. The concept is very simple:

  • IPokemonRepository – This is simply a coding convention that we don’t really need. You could easily create a repository without an interface. We create interfaces to provide Dependency Injection and polymorphism. These are not required though and simply add better flexibility. Although it is bad convention, you could easily new this class up somewhere else.
  • DataContext – Since we are abstracting away our database (remember?), we need to actually bring in the database. If you look throughout our codebase _context (fancy word for “database”) is providing a way to get “things” from the database.
  • Constructor – This one is harder to spot, but look just above the middle. Notice that function and our class have the same name? That is a constructor and provides Dependency Injection. Dependency Injection is another fancy word for “bring in the database when this class is created”. We need a constructor because the functions like GetPokemon, GetPokemons rely on our database therefore we need the context to be there before anything else. That is the whole entire idea behind constructors. Similar to “pre-heating an oven”, certain steps need to occur before we can use our functions and methods.

Conclusion

Repository pattern is one of the most important patterns in any OOP language. If you devote any time to learning design patterns make sure you learn it before the others. Hope you enjoyed. Happy coding!

Posted in C#

Leave a Reply

Your email address will not be published. Required fields are marked *