Introduction
When building large applications in ASP.NET Core, we must follow clean architecture principles.
If we directly write database code inside controllers, the project becomes:
Difficult to maintain
Hard to test
Not scalable
To solve this, developers use:
👉 Repository Pattern
In this article, we will understand:
What is Repository Pattern?
Repository Pattern is a design pattern that:
👉 Separates data access logic from business logic.
Simple meaning:
Instead of writing database code inside controller,
We create a separate class called Repository.
Without Repository Pattern
Controller directly accessing database:
public class ProductController : Controller
{
private readonly ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var products = _context.Products.ToList();
return View(products);
}
}
Problem:
Controller is directly dependent on database.
With Repository Pattern
Step 1 – Create Interface
public interface IProductRepository
{
IEnumerable<Product> GetAll();
}
Step 2 – Implement Repository
public class ProductRepository : IProductRepository
{
private readonly ApplicationDbContext _context;
public ProductRepository(ApplicationDbContext context)
{
_context = context;
}
public IEnumerable<Product> GetAll()
{
return _context.Products.ToList();
}
}
Step 3 – Register in Program.cs
builder.Services.AddScoped<IProductRepository, ProductRepository>();
Step 4 – Use in Controller
public class ProductController : Controller
{
private readonly IProductRepository _repository;
public ProductController(IProductRepository repository)
{
_repository = repository;
}
public IActionResult Index()
{
var products = _repository.GetAll();
return View(products);
}
}
Now controller does NOT know about database.
Clean separation 👍
How It Works
1️⃣ Controller talks to Repository
2️⃣ Repository talks to Database
3️⃣ Data is returned to Controller
4️⃣ Controller sends data to View
Why Use Repository Pattern?
✔ Clean architecture
✔ Loose coupling
✔ Easy unit testing
✔ Better maintainability
✔ Follows SOLID principles
Real-Life Example
Think of a Library:
Librarian does not go inside storage room.
He asks storage manager.
That is Repository Pattern.
Without vs With Repository
| Without Repository | With Repository |
|---|
| Controller handles DB | Separate layer |
| Hard to test | Easy to test |
| Tight coupling | Loose coupling |
| Messy code | Clean structure |
Conclusion
Repository Pattern is very important for professional ASP.NET Core development.
It helps to:
✔ Separate concerns
✔ Write clean code
✔ Improve project structure
✔ Make application scalable