This video is available to students only

Implementing Generic Repository

In this lesson, we're going to implement generic repository to our application

Generic Repository#

We discussed how both of our repositories, courses and categories are doing exactly the same job; to get list of data from our database. It's not a problem when we have a limited number of controllers, but when the project gets bigger, we write almost the same code all over again. The only difference is the Include statement which can differ and the type such as Categories and Controllers.

What we can do with the Generic Repository is to use a placeholder in place of our type. When the code compiles, the generic placeholder will be replaced with the actual type. We just have to specify the type here and everything else will be taken care of automatically.

Without wasting any further time, let's create our Generic Repository Interface. If we open our interfaces, you see the only difference is the type. We have Category in the Category Repository Interface and Course in the Course Repository Interface. Of course, our GetCategoryByIdAsync method takes an integer id as a parameter and GetCourseByIdAsync method takes a Guid. No problem, we can use a dynamic parameter in our Generic repository and later do the casting of the type.

Let's create a new interface and let's call it IGenericRepository. First of all, we will write our generic type T inside the angle brackets. T stands for type. You can call it anything really, but t for type sounds straightforward. We just have to make two methods here. The first one returns the IReadOnlyList. We can write Task IReadOnlyList and here, the type will be T which is dynamic and we can call it ListAsync(). The second one will return a single type and will accept an id. We can write Task of type T. Let's call it GetByIdAsync and pass a dynamic parameter id; we are using dynamic because our Category table has id of type int and Courses table has Id of type Guid.

Now let's do the import using quick fix. Import task from System.Threading.Tasks and IReadOnlyList from System.Collections.Generic. We now have just one repository instead of two. Let's do the implementation of this repository now.

Start a new discussion. All notification go to the author.