Repository Pattern in .NET Core

Repository pattern is an abstraction to the data access layer it hides the details about how data is saved or retrieved from the underlying data source the details about how the data is retrieved is present in the repository. You may have different repositories based on how you want to retrieve data from different data sources.

For doing this you need to define an interface let’s look into the following example,


using System;

This interface is an abstraction against which you will write a code for defined methods. Defining an interface in repository pattern need to specify,

What operations are supported by the repository

As we know interface defines what is can do but not specify how it does so the implementations for the defined methods will be provided class that implements this method. Let's check the implementation of class which is using this interface,


using Microsoft.EntityFrameworkCore;

As you see over here first you need to inject your AppDbContext class using constructor injection then provide an implementation for the methods defined in the repository interface.

Finally, we need to tie repository classes and implementation classes together as per dependency injection for that need to add this in the ConfigureService method of the startup class.

public void ConfigureServices(IServiceCollection services)

As per this code, we provided the implementation class for respected repository So .Net core provides an instance of ProductRepository when the IProductRepository instance is requested.

Benefits of repository pattern:

1) Code maintainability

2) Loosely coupled system

Thank You, See you in the next article !!

You can reach out to me here,



If you want some technical topics to be discussed with group of participants please raise a request on following link:

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *