Understanding the Repository Design Pattern in .NET Core

The Repository Design Pattern is a commonly used design pattern in software development that provides an abstraction layer between the business logic and data access layers in an application. It helps in organizing the data access logic and business logic by keeping them separate. The repository acts as a gateway for retrieving data from databases or other storage mechanisms.

Advantages of Using Repository Design Pattern

  1. Separation of Concerns: This pattern clearly separates the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model.
  2. Centralized Data Access: The Repository pattern allows you to centralize all data access logic, making it easier to maintain.
  3. Reduces Code Duplication: By using a central repository, repetitive code for data access methods can be reduced significantly.
  4. Increased Testability: Having a layer separate from the business logic allows for easier unit testing.

Implementing the Repository Design Pattern in .NET Core

Let's dive into an example of implementing the Repository Design Pattern in a .NET Core application. We will create a simple project called Codingvila.RepositoryDemo with a repository that handles operations for an Book entity.

Step 1. Create a .NET Core Project

First, create a new .NET Core Web API project.

dotnet new webapi -n Codingvila.RepositoryDemo
cd Codingvila.RepositoryDemo

Step 2. Define the Book Entity

Create a new class in the Models directory.

namespace Codingvila.RepositoryDemo.Models
{
    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public int Year { get; set; }
    }
}

Step 3. Create the Repository Interface

Define an interface for the repository in a new folder called Repositories.

using Codingvila.RepositoryDemo.Models;
using System.Collections.Generic;

namespace Codingvila.RepositoryDemo.Repositories
{
    public interface IBookRepository
    {
        Book GetBook(int id);
        IEnumerable<Book> GetAllBooks();
        void AddBook(Book book);
        void UpdateBook(Book book);
        void DeleteBook(int id);
    }
}

Step 4. Implement the Repository

Create a concrete implementation of the IBookRepository.

using Codingvila.RepositoryDemo.Models;
using System.Collections.Generic;
using System.Linq;

namespace Codingvila.RepositoryDemo.Repositories
{
    public class BookRepository : IBookRepository
    {
        private readonly List<Book> _books = new List<Book>();

        public BookRepository()
        {
            // Adding some initial books
            _books.Add(new Book { Id = 1, Title = "Codingvila.com", Author = "Nikunj Satasiya", Year = 2024 });
            _books.Add(new Book { Id = 2, Title = "Introduction to .NET Core", Author = "Nikunj Satasiya", Year = 2024 });
        }

        public Book GetBook(int id)
        {
            return _books.FirstOrDefault(b => b.Id == id);
        }

        public IEnumerable<Book> GetAllBooks()
        {
            return _books;
        }

        public void AddBook(Book book)
        {
            _books.Add(book);
        }

        public void UpdateBook(Book book)
        {
            var index = _books.FindIndex(b => b.Id == book.Id);
            if (index != -1)
            {
                _books[index] = book;
            }
        }

        public void DeleteBook(int id)
        {
            var book = GetBook(id);
            if (book != null)
            {
                _books.Remove(book);
            }
        }
    }
}

Step 5. Register the Repository in Startup

In the Startup.cs, register the repository with the dependency injection system.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IBookRepository, BookRepository>();
    services.AddControllers();
}

Summary

The Repository Design Pattern provides an excellent way to abstract data access in a .NET Core application, making your code cleaner, more maintainable, and easier to test. In our Codingvila.RepositoryDemo example, we have effectively separated the concerns of data access from the business logic, which is a crucial aspect in larger and more complex applications.


Similar Articles
Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.