Application Architecture - Generic Repository
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
Server Architecture - Distributing Projects
Server Structure An interface is a middleman between the browser and the server. It sends a request to a server and handles the response from it. The interface has a dependency on the infrastructure which also has a dependency on the application core proje
jin-co.tistory.com
Implementing MVC Pattern
Application Architecture - MVC
Separation of concern make our code reusable and easier to manager. In that sense, it is considered a good practice to separate business logic and data handling. MVC pattern is one of such implementations that divides an application into three major parts
jin-co.tistory.com
Creating Repository
Application Architecture - Repository
It is a good practice to separate business logic and data handling. Entity Framework provides an MVC pattern to separate them. However, as the size of a project grows, adding data handling codes directly in the controller file creates duplicate codes and b
jin-co.tistory.com
Creating an Interface
Application Architecture - Repository with Service
An Interface is a kind of contract that specifies what the application needs. Let's see how we can use an interface with the repository pattern. Project Configurations Creating a Project with MVC Pattern Server Architecture - Distributing Projects Server S
jin-co.tistory.com
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