Manage shopping cart
This tutorial is a continuation of the previous tutorial. You are going to learn how to create a service using the Dependency Injection technique. In this tutorial:
- Create a cart service with Dependency Injection.
- Allow users to put items to the cart.
- Allow users to review their carts.
You can download the example code used in this topic on GitHub.
Create a cart service
This cart service will hold the information about the product which is selected by the user. This is also known as storing the website's state. There are many places to store that state. For the sake of simplicity, we are going to store the website's state in the memory.
- Create a new class
CartState.cs
as follows:
public class CartState
{
private readonly HttpClient _httpClient;
public List<Product> SelectedItems { get; set; } = new();
public CartState(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task AddProductToCartAsync(Guid productId)
{
if (SelectedItems.Any(p => p.Id == productId) is false)
{
var products = await _httpClient.GetFromJsonAsync<List<Product>>("sample-data/products.json") ?? new();
var product = products.First(p => p.Id == productId);
SelectedItems.Add(product);
}
}
}
- Register the
CartState
to the Dependency Injection. Open your Program.cs
and add the following code:
builder.Services.AddScoped<CartState>();
Allow users to put items to the cart
Once you have the cart service, the next step is to let the users store their cart information.
- Inject the cart service into the
ProductDisplay.razor
we have created in the previous tutorial.
@inject CartState CartState
- Add a parameter to indicate if the component should render the Buy button and define the Buy button UI.
...
@if (DisplayBuyButton)
{
<button class="btn btn-primary" type="button" @onclick="_ => CartState.AddProductToCartAsync(Product.Id)">Buy</button>
}
...
@code {
...
[Parameter]
public bool DisplayBuyButton { get; set; } = false;
}
- Enable the Buy button. Open the
ProductList.razor
and pass the DisplayBuyButton="true"
to the Product
component.
...
<ProductDisplay Product="product" DisplayBuyButton="true"/>
You can see the following result:

Allow users to review their carts
After the user is able to put product to the cart, we will let them review their cart.
- Create a new Razor Component
Checkout.razor
.
- Inject the cart service to the component.
@inject CartState CartState
- Define the UI to show the cart.
<span>You have @CartState.SelectedItems.Count item(s) in your cart.</span>
@foreach (var selectedItem in CartState.SelectedItems)
{
<ProductDisplay Product="selectedItem" />
}
You can see the following result when you put some products in the cart:
