The repository pattern has a static type so whenever we create an entity, we have to create a repository as well. A generic is a way to restrict to a type or to dynamically change types. Let's see how we can use a generic repository for multiple entities
Project Configurations
Creating a Project with MVC Pattern
Implementing MVC Pattern
Creating Repository
Creating an Interface
Creating a Generic Interface
Create a generic interface
Add a type to the interface with a restriction (without the restriction, you will see an error later when implementing methods in the implementation class)
public interface IGenericRepo<T> where T : <className>
Add needed methods
Creating a Generic Repository
Add a repository class under the infrastructure folder
Inherit from the generic interface and implement the methods
public class GenericRepo<T> : IGenericRepo<T> where T:Item
{
public List<T> GetAll()
{
throw new NotImplementedException();
}
}
To set the types, use 'Set<T>'
Adding the Interface as a Service
We need to add the interface in the Program.cs as a service to use it. Add the code below
builder.Services.AddScoped(typeof(IGenericRepo<>), typeof(GenericRepo<>));
Call the Interface in the Controller Class
A normal repository pattern looks as below, replace the repository with the generic interface
private readonly IGenericRepo<Item> _itemRepo;
public StoreController(IGenericRepo<Item> itemRepo)
{
this._itemRepo = itemRepo;
}
Call the method
[HttpGet]
public List<Item> GetItems()
{
return _itemRepo.GetAll();
}
In this writing, we have seen how we can use the MVC generic repository pattern in .NET with EntityFramework
'Backend > .NET' 카테고리의 다른 글
Relational DB - Getting Data including Data from Other Entities (Generic Repository Pattern) (0) | 2023.04.15 |
---|---|
Relational DB - Getting Data including Data from Other Entities (Repository Pattern) (0) | 2023.04.12 |
Application Architecture - Repository with Service (0) | 2023.04.07 |
Adding Configurations When Creating a Database (2) | 2023.03.31 |
Application Architecture - Repository (0) | 2023.03.30 |