본문 바로가기

Backend/.NET

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 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 makes our code reusable and easier to manage. In that sense, it is considered a good practice to separate business logic and data handling. MVC pattern is one such implementation that divides an application into three major parts (mod

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

Using the Interface

Creating an Interface

Create a folder to hold an interface class

Add an interface in the folder

Add needed methods

Inheritance

Go to the repository and add the interface as a parent, and implement the methods you created in the interface

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<IItemRepo, ItemRepo>();

Call the Interface in the Controller Class

A repository pattern without an interface looks as below, replace the repository with the interface

private readonly IItemRepo _repo;
public StoreController(IItemRepo repo)
{
  this._repo = repo;
}

Call the method

[HttpGet]
public ActionResult<List<Item>> GetItems()
{
  return _repo.GetItems();
}

 

In this writing, we have seen how we can use the MVC repository pattern in .NET with EntityFramework

 

 

 

728x90
반응형