You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
11 KiB
11 KiB
marp | paginate | math | theme | title |
---|---|---|---|---|
true | true | mathjax | buutti | N. MVP Pattern and Repositories |
MVP Pattern and Repositories
The MVC Pattern
- For creating APIs, we now know how to
- set up an ASP.NET Core web application,
- set up routes with attributes to connect request URIs with methods,
- respond with HTTP responses
- The problem is that all this functionality is scattered here and there around the program, meaning we have no structure to what we are doing
- In order to write production level code with ASP.NET, your API should follow the MVC pattern
What is the MVC Pattern?
- MVC is a software architectural pattern, an acronym for Model - View - Controller
- Traditionally used for desktop graphical user interfaces
- Helps to enforce separation of concerns
- When an entity in code has only a single job:
- It is easier to read and write
- It is easier to test and debug
\Rightarrow
It's easier to scale the application in complexity
- When an entity in code has only a single job:
- ASP.NET Core includes an MVC Framework for implementing this design pattern
Model, view and controller
Model
- Representation of data in code
- Can also include some logic to retrieve and save the data
View
- The data that is shown to the client, e.g. a web page
- More often than not different from the Model - client does not need to (and often shouldn't) see all possible data
Controller
- Communicates with the Model and the View
- How the data (models) will be processed before sending it forwards to the client or to the view
MVC implementation
- In an ASP.NET Core API, the pattern is implemented like this:
Model
Models/User.cs
namespace MyApi.Models
{
public class User
{
public int Id {get; set;}
public string Name {get; set;}
}
}
View
{
"id": 1
"name": "Sonja"
}
(Basically just JSON data that ASP.NET can show automatically)
Controller
Controllers/UserController.cs
using Microsoft.AspNetCore.Mvc;
using MyApi.Models;
namespace MyApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetUser(int id)
// ...
}
}
The controller
using Microsoft.AspNetCore.Mvc;
using MyApi.Models;
namespace MyApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
var person = new Person
{
Id = 1,
Name = "Sonja"
};
return Ok(person);
}
}
}
- Here's an extended implementation of the earlier controller, showcasing the HTTP
GET
method - The object that gets sent to the View (the webpage) as a JSON is just hardcoded here, but normally the data comes from a database
Exercise 1. Setting up the Project
- Create a new ASP.NET Core Web API template project. Name it
CourseAPI
. DeleteWeatherForecastController.cs
andWeatherForecast.cs
. - Add a new controller
CoursesController
by right-clicking theControllers
folder and selecting Add > Controller... > API Controller > Empty - Add a new folder
Models
. Inside, add a new class file ( Add > Class... ) namedCourse.cs
- To the Course class, create the properties
int Id
,string Name
andint Credits
Exercise 2. Creating GET
endpoints
- Inside the Controller class, initialize a list of courses with a couple of test courses
- Create endpoints for
GET
requests with URIsapi/courses
andapi/courses/{id}
which return all courses and a single course with a corresponding ID, respectively
Repositories
Accessing data with repositories
- When following the separation of concerns principle, the controllers or models should NOT be accessing the database directly
- Instead, the web app should have some kind of repository for reading from and writing to the database
- (Not to be confused with a Git repository!)
- For now, we can just create a mock repository to a new folder called
Repositories
for our needs, and make it static so that it can be accessed everywhere- Later on, we will add services to make the repository available within our program via dependency injection
Repository Example
// Repositories/ContactRepository.cs
public class MockRepo
{
// Replace this later on with a database context
private List<Contact> Contacts { get; set; }
// Constructor to initialize contact list
private MockRepo()
{
Contacts = new List<Contact>();
}
// Replace this later on with dependency injection
public static MockRepo Instance { get; } =
new MockRepo();
public List<Contact> GetContacts() => Contacts;
// Update database here later
// Other methods to read/write from database
// ...
}
// Controllers/ContactsController.cs
// ...
[HttpGet]
public List<Contact> Get()
{
return MockRepo.Instance.GetContacts();
}
// ...
- At this point, implementation of the "database" is up to you
- Later, a real database is added
Exercise 3: Using a Repository
Continue working on CourseAPI.
- Within the solution, create a folder called
Repositories
- Add a mock repository to the folder. Move the course list from the controller to the repository to simulate our database for now. Add methods to get all courses in the list and a single course by ID.
- Modify the controller so that it uses the repository for getting courses.
Services
Repository, as a service
- Services and dependency injection (DI) have been introduced earlier in this training
- Recap: DI allows for loose coupling between classes and their dependencies
- This decreases complexity, makes refactoring easier and increases code testability
- DI is used in ASP.NET to distribute services to classes in a controlled way
- Let's get started by making a repository service
- Recap: Repositories are the interface for handling operations to a database
- Repositories should be accessible within the API from multiple controllers
- Logical step is to make it a service!
Service interface
- Add all methods of the service to the interface:
public interface IContactRepository { Contact GetContact(int id); List<Contact> GetContacts(); void AddContact(Contact contact); void UpdateContact(int id, Contact contact); void DeleteContact(int id); // UpdateDataBase() later on... }
- Next, we'll create a class that implements this interface.
Implementing the interface
public class ContactRepository : IContactRepository
{
// Replace this with database context in a real life application
private static List<Contact> Contacts = new List<Contact>
{
new Contact{Id=0, Name="Johannes Kantola", Email="johkant@example.com"},
new Contact{Id=1, Name="Rene Orosz", Email="rene_king@example.com"}
};
public void AddContact(Contact contact) => Contacts.Add(contact);
public void DeleteContact(int id) =>
Contacts = Contacts.Where(c => c.Id != id).ToList();
public Contact GetContact(int id) => Contacts.FirstOrDefault(c => c.Id == id);
public List<Contact> GetContacts() => Contacts;
public void UpdateContact(int id, Contact newContact) =>
Contacts = Contacts.Select(c => c.Id != id ? c : newContact).ToList();
}
Adding the service to Program.cs
- The service is now ready to be added to the container in the Program.cs file:
// ... builder.Services.AddSingleton<IContactRepository, ContactRepository>(); builder.Services.AddControllers().AddNewtonsoftJson(); // ...
Using the service in a controller
- Add the service to your controller by creating a constructor and passing it as a parameter:
public class ContactsController : ControllerBase { private readonly IContactRepository _contactRepository; public ContactsController(IContactRepository contactRepository) { _contactRepository = contactRepository; } }
- If you need to add more services to the controller later, you can just add them as a parameter as well - the order of parameters does not matter!
Consuming the service in endpoints
- Your service is now ready to be consumed by the controller
- No need to use
MockRepo.Instance.GetContacts()
anymore![HttpGet("{id}")] public IActionResult GetContactById(int id) { Contact contact = _contactRepository.GetContact(id); if (contact == null) { return NotFound(); } return Ok(contact); }
Exercise 4: A real repository
Continue working on CourseAPI.
- Create an interface
ICourseRepository
with methods for getting a single course or all courses. Rename your mock repository toCourseRepository
and make sure the interface is fully implemented. - Add
CourseRepository
as a service, and refactor the controller to use methods forICourseRepository
Wrapping Things Up
At this point, the flow of your API should be in line with this chart:
Project hierarchy
- In solution explorer, the project hierarchy would look like this.
- Once you start adding new classes, they should have their own models and controllers
- One repository can store multiple models, and there can be multiple repositories
- Every server/database/API you use should have its own repository!
What the Heck Does This Do?
- A lot of the functionality in ASP.NET comes from the base class library
- When starting out, trying to remember all the methods and what does what can feel overwhelming
- If you ever end up getting confused what any method does, Ctrl + click Type name to go to definition
- There is always a summary about the method
- Also looking up the method from Microsoft documentation is helpful