Add a data store
Add a data store
Before you start to implement a web API for pizza, you need to have a data store on which you can perform operations.
You need a model
class to represent a pizza in inventory. The model contains properties that represent the characteristics of a pizza. The model is used to pass data in the web API and to persist pizza options in the data store.
In this unit, that data store is a simple local in-memory caching service. In a real-world application, you would consider using a database, such as SQL Server, with Entity Framework Core.
Create a pizza model
Run the following command to create a Models folder:
Select the Models folder in Visual Studio and add a new file called Pizza.cs.
The project root now contains a Models directory with an empty Pizza.cs file. The directory name Models is a convention. The directory name comes from the model-view-controller architecture that the web API uses.
Add the following code to Models/Pizza.cs to define a pizza. Save your changes.
Add a data service
Run the following command to create a Services folder:
Select the folder in Visual Studio Code and add a new file called PizzaService.cs.
Add the following code to Services/PizzaService.cs to create an in-memory pizza data service. Save your changes.
This service provides a simple in-memory data caching service with two pizzas by default. Our web API will use that service for demo purposes. When you stop and start the web API, the in-memory data cache will be reset to the two default pizzas from the constructor of
PizzaService
.
Notice the use of static keyword on the service class! Static objects are created only once - whenAPI is called for the first time. It remains in-memory until it is shut down
Build the web API project
Save the files and run the following command to build the app:
The build succeeds with no warnings. If the build fails, check the output for troubleshooting information.
In the next unit, you'll create a controller that will use the Pizza
model and PizzaService
class.
Last updated